package main
import (
"fmt"
)
func InsertSort(a []int) {
if len(a) == 0 {
return
}
length := len(a)
for i := 1; i < length; i++ {//默认第一个排序是正确的
j := i
target := a[i]
for j > 0 && target < a[j-1] { //比较移位
a[j] = a[j-1] //移位
j--
}
a[j] = target
fmt.Println(a)
}
}
func main() {
a := []int{34, 67, 89, 2, 45}
InsertSort(a)
}
结果
➜ insert time go run insertSort.go
[34 67 89 2 45]
[34 67 89 2 45]
[2 34 67 89 45]
[2 34 45 67 89]
go run insertSort.go 0.14s user 0.12s system 90% cpu 0.285 total