C/C++ Arena

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.

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