awelgorithms

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
  1. save 1
  2. move 9 to index 0 → [9, 4]
  3. sift 9 vs 4 → [4, 9]

Result: 1

four items

a = [1, 4, 9, 7], extract
  1. save 1
  2. move 7 to index 0 → [7, 4, 9]
  3. sift 7 vs 4 → [4, 7, 9]

Result: 1

two items

a = [4, 9], extract
  1. save 4
  2. move 9 to index 0 → [9]
  3. 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.