package InsertionSort
func insertionSort(nums []int) {for j := 1; j < len(nums); j++ {key := nums[j]
// insert A[j] into the sorted sequence A[0..j-1]
// A[0..j-1] 升序排序
i := j - 1
// key 比曾经排好序的 A[0..j-1] 小,将 key 插入适宜的地位
// 当找到适宜的地位退出循环
for i >= 0 && nums[i] > key {
// 整体向右挪动 yiwei
nums[i+1] = nums[i]
i--
}
// A[i+1] 为空缺地位
nums[i+1] = key
}
}
package InsertionSort
import (
"math/rand"
"testing"
"time"
)
func TestInsertionSort(t *testing.T) {var input [100]int
r := rand.New(rand.NewSource(time.Now().Unix()))
// 初始化数组 input[]
for i := 0; i < 100; i++ {input[i] = r.Intn(1000)
}
insertionSort(input[:])
for i := 0; i < 10; i++ {println(input[i])
}
}