Documentation
¶
Overview ¶
Package heap provides a persistent (immutable) priority queue backed by a pairing heap, parameterized by a comparator function.
Based on Stone's Algorithms for Functional Programming (Ch 4). The pairing merge strategy (Stone's heap-list-merger) gives O(1) insert and merge with O(log n) amortized delete-min.
Create heaps with New or From. The zero value is a valid empty heap for queries (IsEmpty, Min, Len) but panics on Insert, DeleteMin, and Merge because no comparator is available.
Use slice.Asc and slice.Desc from the slice package to build comparators:
h := heap.New(slice.Asc(Widget.Priority)) // min-heap by priority h := heap.New(slice.Desc(Widget.Priority)) // max-heap by priority
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Heap ¶
type Heap[T any] struct { // contains filtered or unexported fields }
Heap is a persistent priority queue. Operations return new heaps; the original is unchanged. The comparator determines ordering: negative means the first argument has higher priority.
func (Heap[T]) Collect ¶
func (h Heap[T]) Collect() []T
Collect returns all elements in sorted order. O(n log n). Returns nil for an empty heap. Stone's fold-heap applied with list + prepend.
func (Heap[T]) DeleteMin ¶
DeleteMin returns a new heap with the minimum element removed. Returns an empty heap (with comparator) if called on an empty heap. O(log n) amortized.
func (Heap[T]) Insert ¶
Insert returns a new heap with t added. O(1). Stone's heap-adjoiner: create a singleton bush, merge with root.
func (Heap[T]) Merge ¶
Merge returns a new heap combining h and other. O(1). Uses h's comparator. Both heaps must use the same ordering for correct results. Stone's merge-heaps.