Animation10 min
Bubble-Up / Sink-Down
The tree and its backing array move together.
A heap is one structure wearing two costumes: a binary tree you reason about, and a flat array the computer actually stores. This animation shows both at once, and every swap happens in both views simultaneously.
Insert appends the new value at the next free array slot — which is exactly the next open leaf position in the tree. Then it bubbles up: compare with the parent at index (i - 1) // 2, swap while smaller, stop when the parent is smaller or it reaches the root.
Pop ejects the root, teleports the last leaf into the root slot, then sinks it down — swapping with the smaller of its two children at 2i + 1 and 2i + 2 until both children are bigger.
What to watch for:
- Every tree swap flashes a matching pair of array cells. There is no separate tree in memory — the arrows are just index arithmetic.
- Each operation touches one root-to-leaf path only. Count the swaps: never more than the tree's height, which is why push and pop are O(log n).
- After every operation, check the one rule — every parent smaller than its children — and notice the array is still not sorted.