Sift-up swaps in a binary heap

A min-heap is stored as the array [1, 3, 2, 7, 8, 5, 9] (index 00 is the root; the children of index ii are at 2i+12i+1 and 2i+22i+2). You insert the value 0 at the next free slot (index 77) and sift it up to restore the heap. How many swaps does the sift-up perform?

Show hints (2)+
  1. Parent of index ii is ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor; swap while child << parent.
  2. Trace the path 7→3→1→07 \to 3 \to 1 \to 0.

Answer

Reveal answer →

3

Create a free account to see the full worked solution and track your progress.

Interview format: Hedge Fund Quant, Prop Trading

Related questions