文章目录
GoLang之标准库container/heap包
本文基于Windos系统上Go SDK v1.17.5进行讲解
1.container/heap包介绍
2.heap.Iterface接口
3.heap.Init函数
Init函数用于堆初始化,接受一个实现了heap.Interface的对象,并初始化为一个堆,所有的堆在使用之前都需要进行初始化,Init函数定义为:
传入的参数是heap.Interface
4.heap.Push函数
5.heap.Pop函数
6.heap.Remove函数
7.heap.Fix函数
8.heap.down函数
func down(h Interface, i0, n int) bool {
i := i0
for {
j1 := 2*i + 1
if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
break
}
j := j1 // left child
if j2 := j1 + 1; j2 < n && h.Less(j2, j1) {
j = j2 // = 2*i + 2 // right child
}
if !h.Less(j, i) {
break
}
h.Swap(i, j)
i = j
}
return i > i0
}
9.heap.up函数
func up(h Interface, j int) {
for {
i := (j - 1) / 2 // parent
if i == j || !h.Less(j, i) {
break
}
h.Swap(i, j)
j = i
}
}