std.heap

A comparison-ordered binary heap.

Importuse std.heap

Functions

fn heapify<T>(array: [T], less: fn(T, T) -> bool)#

Reorders array into heap order under less, in place (Floyd, O(n)).

  • array: Array reordered in place into heap order.
  • less: Ordering predicate; less(a, b) puts a closer to the top.
let tasks = [5, 1, 4, 2]
std.heap.heapify(tasks, |a, b| a < b)
println(std.heap.peek(tasks)) // 1
std.heap.push(tasks, 0, |a, b| a < b)
println(std.heap.pop(tasks, |a, b| a < b)) // 0
println(std.heap.pop(tasks, |a, b| a < b)) // 1
fn push<T>(heap: [T], value: T, less: fn(T, T) -> bool)#

Inserts value, restoring heap order (O(log n)).

  • heap: Heap to insert into, mutated in place.
  • value: Element to add.
  • less: Ordering predicate, matching the one the heap was built with.
let heap: [int] = []
std.heap.push(heap, 7, |a, b| a < b)
std.heap.push(heap, 3, |a, b| a < b)
println(std.heap.peek(heap)) // 3
fn pop<T>(heap: [T], less: fn(T, T) -> bool) -> T#

Removes and returns the top element; errors on an empty heap.

  • heap: Heap to take the top from, mutated in place.
  • less: Ordering predicate, matching the one the heap was built with.
let heap = [3, 1, 2]
std.heap.heapify(heap, |a, b| a > b) // flipped closure: a max-heap
println(std.heap.pop(heap, |a, b| a > b)) // 3
println(std.heap.pop(heap, |a, b| a > b)) // 2
fn peek<T>(heap: [T]) -> T#

The top element without removing it; errors on an empty heap.

  • heap: Heap to inspect; it is left unchanged.