Data structures · real, tested code

Implement a Priority Queue (Binary Heap) in Larzscript

Always get the smallest (or, with a key function, largest/custom-ordered) item next - the classic array-backed binary heap.

heap.heapsort() is a real proof that the heap itself is correct: sorting is just popping every item off in order.

larzscript pkg install heap

Code

import "heap" as heap

let h = heap.new()
heap.push(h, 5); heap.push(h, 1); heap.push(h, 3); heap.push(h, 8)
print(heap.pop(h))
print(heap.peek(h))
print(heap.heapsort([5, 1, 4, 2, 8]))
Output
1
3
[1, 2, 4, 5, 8]