Step 5 of 6
A binary heap by hand
A binary heap is a complete binary tree stored in a plain array. No pointers at all:
index: 0 1 2 3 4 5
parent(i) = (i - 1) / 2 children(i) = 2i + 1, 2i + 2
In a min-heap, every parent is ≤ its children, so the minimum is always at index 0.
- push: append at the end, then sift up: swap with the parent while smaller.
- pop: move the last element to the root, then sift down: swap with the smaller child while larger.
Both are O(log n). This is what's inside std::priority_queue.
Your turn: implement MinHeap::push, MinHeap::pop (assume non-empty) and top.
Previous: Level order with a queue Next: Challenge: a trie for autocomplete