Heap = array + parent≤child rule. Insert → sift up; extract-min → sift down. Tree & array side by side, step by step. The priority queue engine. An…
Why it matters
Heaps sit behind Dijkstra, A*, task schedulers, heapsort, top-k and merging many sorted lists. Its tree has no pointers: positions are index arithmetic, 2i + 1, 2i + 2, (i − 1) >> 1, so every operation touches one path log n high.
The key idea
A heap is an array that keeps parent ≤ child
Common mistakes
Searching for a value in the heap is very slow, though it is supposed to be fast A heap is only fast for the smallest (or largest). Membership stays O(n). Need it? Keep a hash set or a search tree beside it.
The heap gets weird, child and parent indices stop matching after a manual insert or extract Insert always into the last slot, extract always fills the root with the last element. shift() or inserting in the middle moves slots and breaks the 2i + 1 mapping.
Assuming a heap is fully sorted, but printing it looks scrambled A heap only promises parent ≤ child (root = minimum); siblings are not in order. Need a full order? Pop repeatedly (heapsort) or sort the array.
Try it in this playground
A push that climbs far A small number: two swaps or more, one per level.
A push that settles at once A large number: its parent is smaller already, zero swaps.
Pop twice What comes out is always the smallest: that is heapsort.
Heapify a list Compare its swaps with pushing one by one.