go heap分析,不废话

130 阅读2分钟

底层是使用切片模拟堆,heap包封装了Init,Push,Pop

func Init(h Interface) {
    // heapify
    n := h.Len()
    for i := n/2 - 1; i >= 0; i-- {
       down(h, i, n)
    }
}
func Push(h Interface, x any) {
    h.Push(x)
    up(h, h.Len()-1)
}
func Pop(h Interface) any {
    n := h.Len() - 1
    h.Swap(0, n)
    down(h, 0, n)
    return h.Pop()
}
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
    }
}

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
}

Init,Push,Pop需要用户实现h.Len 而up,dowm需要用户手动实现h.Less和h.Swap

结合实例:

package main

import (
    "container/heap"
    "fmt"
)

// An IntHeap is a min-heap of ints.
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x any) {
    // Push and Pop use pointer receivers because they modify the slice's length,
    // not just its contents.
    *h = append(*h, x.(int))
}

func (h *IntHeap) Pop() any {
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[0 : n-1]
    return x
}

// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
func main() {
    h := &IntHeap{2, 3, 5}
    //fmt.Printf("original h = %+v\n", h)

    heap.Init(h)
    //fmt.Printf("Init h = %+v\n", h)

    heap.Push(h, 1)
    //fmt.Printf("push(1) = %+v\n", h)

    //fmt.Printf("minimum: %d\n", (*h)[0])
    for h.Len() > 0 {
       fmt.Printf("%d ", heap.Pop(h))
    }
}

可以分析,堆的构建和修改过程如下

  • Init方法对堆初始化,

  • 之后heap.Push和heap.Pop都会:

    • 调用用户实现的h.Push或者h.Pop方法实现元素的加入和删除,

    • 之后再在内部进行堆的维护(使用up,down结合h.Swap等)

注意: 实现h.Pop时,要注意heap.POp是先进行了swap和down,之后才调用了h.Pop,这与heap.Push是相反的,因此用户实现h.Pop就是要把最后一个元素弹出即可(对应的就是swap和down之前的堆顶元素,即最小元素),而h.Push就是把元素添加到末尾