Extract the heap root
Updated
Save a[0], copy a[size-1] onto a[0], size--, then sift down from 0. Return the saved root. Sift down uses left 2*i+1 and right 2*i+2.
What to focus on
Extract yields the old min, not the new a[0]. From [1, 4, 9] you get 1 and heap [4, 9]. From [1, 4, 9, 7] you get 1 and heap [4, 7, 9].
Worked examples
three items
a = [1, 4, 9], extract- save 1
- move 9 to index 0 → [9, 4]
- sift 9 vs 4 → [4, 9]
Result: 1
four items
a = [1, 4, 9, 7], extract- save 1
- move 7 to index 0 → [7, 4, 9]
- sift 7 vs 4 → [4, 7, 9]
Result: 1
two items
a = [4, 9], extract- save 4
- move 9 to index 0 → [9]
- no child to sift
Result: 4
Try it
Write extract(a). a is a non-empty min-heap. Save a[0], move the last leaf to index 0, then sift down. left(i)=2*i+1. right(i)=2*i+2. Return the old root. [1, 4, 9] → 1 [1, 4, 9, 7] → 1 [4, 9] → 4
The heap is a non-empty min-heap of 2–6 items. left(i)=2*i+1. right(i)=2*i+2. A child exists iff that index < size.