func left(i int) int {
return 2*i + 1
}
func right(i int) int {
return 2*i + 2
}
//建堆
func buildHeap(a []float64) {
length := len(a)
for i := length / 2; i >= 0; i– {
maxHeap(i, a, length)
}
}
//堆化,保证每个父节点都大于子节点
func maxHeap(p int, a []float64, length int) {
l := left§
r := right§
index := p
if l < length && a[l] > a[index] {
index = l
}
if r < length && a[r] > a[index] {
index = r
}
if index != p {
a[index], a[p] = a[p], a[index]
maxHeap(index, a, length)
}
}
func main(){
a := []int{1, 5, 6, 4, 7, -8, 77, -9, 6, 1, 0, 3}
buildHeap(a)
fmt.Println(a)
length := len(a)
//堆排,父节点是最大的,每次将父节点放到最后一个元素,再将剩余元素堆化
for length > 0 {
a[0], a[length-1] = a[length-1], a[0]
length–
maxHeap(0, a, length)
}
fmt.Println(a)
}