The minmaxheap module implements a heap data structure that can be used as a priority queue with fast O(log N) pop() operations for smallest and largest elements.
Initial build is linear in number of elements, add() is O(log N) and read access for smallest and largest element is O(1).
Basic usage
import minmaxheap var # h = toMinMaxHeap[int](@[5, 3, 9, 1, 0]) h = toMinMaxHeap([5, 3, 9, 1, 0]) echo $(h) # @[0, 5, 9, 1, 3] echo h.min # 0 echo h.max # 9 echo h.len # 5 echo h.popMin # 0 echo h.popMax # 9 echo h.len # 3 echo h.min # 1 echo h.max # 5 h.add(8) echo h.len # 4 echo h.popMax # 8 echo h.len # 3 h.clear echo h.len # 0
Usage with custom object
To use a MinMaxHeap with a custom object, the < operator must be implemented.
type O = object key: float # we need < operator defined for elements proc `<`(a, b: O): bool = a.key < b.key var l = initMinMaxHeap[O]() l.add(O(key: 1.2)) l.add(O(key: 0.9)) l.add(O(key: 3.3)) echo l.popMax # (key: 3.3) echo l.popMin # (key: 0.9)
Types
MinMaxHeap[T] = distinct seq[T]
Procs
proc initMinMaxHeap[T](): MinMaxHeap[T]
- Create a new empty MinMaxHeap object.
proc toMinMaxHeap[T](h: openArray[T]): MinMaxHeap[T]
- Create a new MinMaxHeap object initialized from an array or a seq.
proc clear[T](h: var MinMaxHeap[T])
- Remove all elements from h, making it empty.
proc len[T](h: MinMaxHeap[T]): int {...}{.inline.}
- Return the number of elements of h.
proc empty[T](h: MinMaxHeap[T]): bool {...}{.inline.}
- Returns true if h.len == 0, false otherwise.
proc add[T](h: var MinMaxHeap[T]; i: T)
- Insert element i into h, maintaining order/invariants.
proc popMin[T](h: var MinMaxHeap[T]): T
- Delete and return smallest element from h, maintaining order/invariants.
proc popMax[T](h: var MinMaxHeap[T]): T
- Delete and return largest element from h, maintaining order/invariants.
proc min[T](h: var MinMaxHeap[T]): T {...}{.inline.}
- Return smallest element from h.
proc max[T](h: var MinMaxHeap[T]): T {...}{.inline.}
- Return largest element from h.
proc `$`[T](h: MinMaxHeap[T]): string
- Turn h into its string representation.