func HeapSort(arr []int, start, end int) {
first := start
hi := end - start
lo := 0
// 建堆
for i := hi / 2; i >= 0; i-- {
heapify(arr, i, hi, first)
}
//数据pop
for i := hi; i >= 0; i-- {
Swap(&arr[first], &arr[first+i])
//将最大的元素放到末位前面的元素需要重新建堆
heapify(arr, lo, i, first)
}
}
func heapify(arr []int, lo, hi, first int) {
root := lo
for {
child := 2*root + 1
if child >= hi {
break
}
if child+1 < hi && arr[child] < arr[child+1] {
child++
}
if arr[root] > arr[child] {
return
}
Swap(&arr[root], &arr[child])
root = child
}
}
func Swap(a, b *int) {
temp := *a
*a = *b
*b = temp
}
主要是建堆得过程