awelgorithms

Sift up after insert

Updated

After append, i = size-1. While i > 0 and a[i] < a[p] with p = Math.floor((i-1)/2), swap and set i = p.

What to focus on

Only the path to the root moves. Siblings are not compared. Stop at index 0 or when the parent is already <= the child.

Worked examples

two swaps

a = [1, 4, 9, 0], i = 3
  1. p=1, 0<4 swap → [1, 0, 9, 4]
  2. i=1 p=0, 0<1 swap → [0, 1, 9, 4]
  3. i=0 stop

Result: [0, 1, 9, 4]

one swap

a = [7, 1], i = 1
  1. p=0, 1<7 swap → [1, 7]
  2. i=0 stop

Result: [1, 7]

no swap

a = [1, 4, 9, 7], i = 3
  1. p=1, 7>=4 stop

Result: [1, 4, 9, 7]

Try it

Write siftUp(a, i). a is the heap after append. i is the new leaf index. parent(i) = Math.floor((i-1)/2). Swap while a[i] < a[parent] and i > 0. Return a. Print each swap. [1, 4, 9, 0] i=3 → [0, 1, 9, 4] [7, 1] i=1 → [1, 7] [1, 4, 9, 7] i=3 → stays

The new leaf is already appended. i is that live index. Heap order holds except along i's path to the root. parent(i) = Math.floor((i-1)/2).