Created
April 2, 2017 21:12
-
-
Save akotlar/675dc80a81e1b8b969a65720752b1dae to your computer and use it in GitHub Desktop.
Insertion sort in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
"strings" | |
) | |
//Usage: insertion-sort 4,3,5,99,16 | |
func main() { | |
numbers := os.Args[1] | |
var arr []int | |
var num int | |
var err error | |
for _, val := range strings.Split(numbers, ",") { | |
num, err = strconv.Atoi(val) | |
if err != nil { | |
log.Fatal("Failed") | |
} | |
arr = append(arr, num) | |
} | |
for j := 1; j < len(arr); j++ { | |
key := arr[j] | |
i := j - 1 | |
for i >= 0 && arr[i] > key { | |
arr[i+1] = arr[i] | |
i = i - 1 | |
} | |
arr[i+1] = key | |
} | |
fmt.Println(arr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment