// heap
typeInterfaceinterface{sort.InterfacePush(xany)// add x as element Len()
Pop()any// remove and return element Len() - 1.
}// sort
typeInterfaceinterface{// Len is the number of elements in the collection.
Len()int// Less reports whether the element with index i
// must sort before the element with index j.
//
// If both Less(i, j) and Less(j, i) are false,
// then the elements at index i and j are considered equal.
// Sort may place equal elements in any order in the final result,
// while Stable preserves the original input order of equal elements.
//
// Less must describe a transitive ordering:
// - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
// - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
//
// Note that floating-point comparison (the < operator on float32 or float64 values)
// is not a transitive ordering when not-a-number (NaN) values are involved.
// See Float64Slice.Less for a correct implementation for floating-point values.
Less(i,jint)bool// Swap swaps the elements with indexes i and j.
Swap(i,jint)}
// Init establishes the heap invariants required by the other routines in this package.
// Init is idempotent with respect to the heap invariants
// and may be called whenever the heap invariants may have been invalidated.
// The complexity is O(n) where n = h.Len().
funcInit(hInterface){// heapify
n:=h.Len()fori:=n/2-1;i>=0;i--{down(h,i,n)}}
根据索引0为根节点初始化的堆,具体流程如下:
获取数组长度
从大到小遍历非叶子节点,进行down操作,向下层进行调整
3.3 down操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
funcdown(hInterface,i0,nint)bool{i:=i0for{j1:=2*i+1ifj1>=n||j1<0{// j1 < 0 after int overflow
break}j:=j1// left child
ifj2:=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}returni>i0}
// Pop removes and returns the minimum element (according to Less) from the heap.
// The complexity is O(log n) where n = h.Len().
// Pop is equivalent to [Remove](h, 0).
funcPop(hInterface)any{n:=h.Len()-1h.Swap(0,n)down(h,0,n)returnh.Pop()}
// Remove removes and returns the element at index i from the heap.
// The complexity is O(log n) where n = h.Len().
funcRemove(hInterface,iint)any{n:=h.Len()-1ifn!=i{h.Swap(i,n)if!down(h,i,n){up(h,i)}}returnh.Pop()}
// Fix re-establishes the heap ordering after the element at index i has changed its value.
// Changing the value of the element at index i and then calling Fix is equivalent to,
// but less expensive than, calling [Remove](h, i) followed by a Push of the new value.
// The complexity is O(log n) where n = h.Len().
funcFix(hInterface,iint){if!down(h,i,h.Len()){up(h,i)}}