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]
Related
larzheapA readable, array-backed binary heap→Implement a Stack and a Queue in LarzscriptThe two most basic linear data structures - last-in-first-out and first-in-first-out - named explicitly instead of just using a bare list.→Implement a Binary Search Tree in LarzscriptInsert values into a binary search tree and read them back in sorted order.→