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])
}
}
相关文章
暂无评论...