Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Insertion sort in Golang
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
You can’t perform that action at this time.