How does downheap restore the heap-order property after removeMin(), and why does it swap with the smaller child?
Downheap moves the key k from the root downwards, each time swapping it with the smaller of the children's keys, until all of k's children have keys ≥ k or k reaches the bottom level. It follows one path down, so it takes $O(\log n)$.
* removeMin() replaces the root with the last node, which then sinks below its smaller child until it fits. *
downheap(r):
while r has a child:
c ← the child of r with the smaller key
if key(c) ≥ key(r): stop
swap the entries of r and c
r ← c
Why the smaller child? After the swap, the child's key becomes the parent of both children. If the larger child were swapped up, it would sit above its smaller sibling, and heap order would be broken right there. Swapping with the smaller child guarantees the new parent is ≤ both.
Example, continuing from removing 2 out of 2 → (5, 6), 5 → (9, 7): the root now holds 7, with children 5 and 6.
- Smaller child is 5, and 5 < 7: swap. Now 5 → (7, 6), with 9 below the 7.
- 7's only child is 9, and 9 ≥ 7: stop.
Ties: if both children have the same key, either choice keeps the heap valid. Implementations often fix one rule anyway, typically "swap with the left child", so that their behaviour is deterministic and tests stay reproducible.
Running time: one swap per level and height $O(\log n)$, so downheap, and with it removeMin, costs $O(\log n)$.
Go deeper:
Binary heap: extract — down-heap (sift-down) with the "swap with the smaller child" rule spelled out.