awelgorithms

Sift down after extract

Updated

From i = 0, let left = 2*i+1 and right = 2*i+2. Pick the smaller live child. If a[i] > that child, swap and continue; else stop.

What to focus on

Always drop toward the smaller child. Stop at a leaf (left >= size) or when both children are >= a[i].

Worked examples

one child

a = [9, 4], i = 0, size 2
  1. left=1 holds 4
  2. right=2 past size
  3. 9>4 swap

Result: [4, 9]

two children

a = [7, 4, 9], i = 0, size 3
  1. left 4, right 9, smaller is 4 at 1
  2. 7>4 swap → [4, 7, 9]
  3. i=1 left=3 past size

Result: [4, 7, 9]

already ordered

a = [1, 4, 9], i = 0, size 3
  1. smaller child is 4
  2. 1<=4 stop

Result: [1, 4, 9]

Try it

Write siftDown(a, i). a is the heap after moving the last leaf to the root. i starts at 0. left(i)=2*i+1. right(i)=2*i+2. Swap toward the smaller live child while a[i] is larger. Return a. Print each swap. Always compare both live children. [9, 4] → [4, 9] [7, 4, 9] → [4, 7, 9] [1, 4, 9] stays

size is the live count after extract. left and right exist iff 2*i+1 and 2*i+2 are < size.