折半插入排序是直接插入排序的升级,在查找插入点时,使用折半查找,代码如下:
func HalfInsertSort(a []int){//折半插入
var j,low,high int
for i := 1;i<len(a);i++ {
a[0] = a[i]
low = 1
high = i-1
for low <= high { //在a[1:i-1]中折半查找插入的位置
mid := (low+high)/2
if a[0] < a[mid] {
high = mid-1
}else{
low = mid +1
}
}
for j = i-1; j>high; j-- {
a[j+1] = a[j]
}
a[j+1] = a[0]
}
fmt.Println(a)
}
测试:
func main(){
a := []int{0,1,4,6,5,2,9,11,34,21,22}
base_sort.HalfInsertSort(a)
//[22 1 2 4 5 6 9 11 21 22 34] 不管a[0]
}