type BinHeap[V cmp.Ordered] struct { maxHeap bool binHeap binHeap[V] }
// NewBinHeap returns a new binary heap. funcNewBinHeap[Vcmp.Ordered](opts ...BinHeapOption[V]) *BinHeap[V] { h := &BinHeap[V]{}
for _, opt := range opts { opt(h) }
return h }
// Len returns the number of elements in the heap. func(h *BinHeap[V]) Push(x V) { h.binHeap.Push(x) sift_up[V](&h.binHeap, h.binHeap.Len()-1, h.maxHeap) }
// Push pushes the element x onto the heap. func(h *BinHeap[V]) Pop() V { n := h.binHeap.Len() - 1 h.binHeap.Swap(0, n) sift_down[V](&h.binHeap, 0, n, h.maxHeap) return h.binHeap.Pop() }
// Len returns the number of elements in the heap. func(h *BinHeap[V]) Len() int { return h.binHeap.Len() }
// Peek returns the element at the top of the heap without removing it. func(h *BinHeap[V]) Peek() (V, bool) { var v V if h.Len() == 0 { return v, false }
// WithMaxHeap returns a BinHeapOption that configures a binary heap to be a max heap. funcWithMaxHeap[Vcmp.Ordered](h *BinHeap[V]) *BinHeap[V] { h.maxHeap = true return h }
// WithMinHeap returns a BinHeapOption that configures a binary heap to be a min heap. funcWithCapacity[Vcmp.Ordered](n int) BinHeapOption[V] { returnfunc(h *BinHeap[V]) *BinHeap[V] { if h.binHeap == nil { h.binHeap = make(binHeap[V], 0, n) } return h } }
// NewBinHeapWithInitial returns a new binary heap with the given initial slice. funcNewBinHeapWithInitial[Vcmp.Ordered](s []V, opts ...BinHeapOption[V]) *BinHeap[V] { h := &BinHeap[V]{} h.binHeap = binHeap[V](s)
for _, opt := range opts { opt(h) }
n := len(s) for i := n/2 - 1; i >= 0; i-- { sift_down[V](&h.binHeap, i, n, h.maxHeap) }