mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 12:58:42 +08:00
docs(heap): add go codes
This commit is contained in:
@ -4,10 +4,25 @@
|
||||
|
||||
package chapter_heap
|
||||
|
||||
// intHeap 是一个由整数组成的堆
|
||||
// 通过实现 heap.Interface 来构建堆
|
||||
// Go 语言中可以通过实现 heap.Interface 来构建整数大顶堆
|
||||
// 实现 heap.Interface 需要同时实现 sort.Interface
|
||||
type intHeap []any
|
||||
|
||||
// Push heap.Interface 的方法,实现推入元素到堆
|
||||
func (h *intHeap) Push(x any) {
|
||||
// Push 和 Pop 使用 pointer receiver 作为参数
|
||||
// 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。
|
||||
*h = append(*h, x.(int))
|
||||
}
|
||||
|
||||
// Pop heap.Interface 的方法,实现弹出堆顶元素
|
||||
func (h *intHeap) Pop() any {
|
||||
// 待出堆元素存放在最后
|
||||
last := (*h)[len(*h)-1]
|
||||
*h = (*h)[:len(*h)-1]
|
||||
return last
|
||||
}
|
||||
|
||||
// Len sort.Interface 的方法
|
||||
func (h *intHeap) Len() int {
|
||||
return len(*h)
|
||||
@ -24,23 +39,7 @@ func (h *intHeap) Swap(i, j int) {
|
||||
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
|
||||
}
|
||||
|
||||
// Push heap.Interface 的方法
|
||||
|
||||
func (h *intHeap) Push(x any) {
|
||||
// Push 和 Pop 使用 pointer receiver 作为参数
|
||||
// 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。
|
||||
*h = append(*h, x.(int))
|
||||
}
|
||||
|
||||
// Top 获取堆顶元素
|
||||
func (h *intHeap) Top() any {
|
||||
return (*h)[0]
|
||||
}
|
||||
|
||||
// Pop heap.Interface 的方法,实现弹出堆顶元素
|
||||
func (h *intHeap) Pop() any {
|
||||
// 待出堆元素存放在最后
|
||||
last := (*h)[len(*h)-1]
|
||||
*h = (*h)[:len(*h)-1]
|
||||
return last
|
||||
}
|
||||
|
||||
@ -77,6 +77,22 @@ func (h *maxHeap) push(val any) {
|
||||
h.siftUp(len(h.data) - 1)
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从底至顶堆化 */
|
||||
func (h *maxHeap) siftUp(i int) {
|
||||
for true {
|
||||
// 获取结点 i 的父结点
|
||||
p := h.parent(i)
|
||||
// 当“越过根结点”或“结点无需修复”时,结束堆化
|
||||
if p < 0 || h.data[i].(int) <= h.data[p].(int) {
|
||||
break
|
||||
}
|
||||
// 交换两结点
|
||||
h.swap(i, p)
|
||||
// 循环向上堆化
|
||||
i = p
|
||||
}
|
||||
}
|
||||
|
||||
/* 元素出堆 */
|
||||
func (h *maxHeap) poll() any {
|
||||
// 判空处理
|
||||
@ -117,22 +133,6 @@ func (h *maxHeap) siftDown(i int) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 从结点 i 开始,从底至顶堆化 */
|
||||
func (h *maxHeap) siftUp(i int) {
|
||||
for true {
|
||||
// 获取结点 i 的父结点
|
||||
p := h.parent(i)
|
||||
// 当“越过根结点”或“结点无需修复”时,结束堆化
|
||||
if p < 0 || h.data[i].(int) <= h.data[p].(int) {
|
||||
break
|
||||
}
|
||||
// 交换两结点
|
||||
h.swap(i, p)
|
||||
// 循环向上堆化
|
||||
i = p
|
||||
}
|
||||
}
|
||||
|
||||
/* 打印堆(二叉树) */
|
||||
func (h *maxHeap) print() {
|
||||
PrintHeap(h.data)
|
||||
|
||||
Reference in New Issue
Block a user