Sorting and searching · Exercise 60 of 100

Min-heap insertion

A min-heap fills a binary tree one level at a time from left to right, and each parent is at most as large as its children. To insert a value, place it in the next open spot and swap it with its parent while it is smaller. Only the path back to the root can need repairs.

Try it yourself

A min-heap is stored level by level in [2, 6, 4, 8, 9, 7, 5]. Append 1 as the left child of 8 and complete the insertion. Which value now occupies the spot where 8 started?

One-step hint

Mark the original slot of 8 on a heap sketch. As the inserted value climbs toward the root, track what moves down into the marked slot.

Worked solution
  1. Swap 1 with 8, then with 6. The second swap moves 6 down into the spot where 8 started.
  2. The final swap exchanges 1 and 2 at the top. It leaves 6 in the original spot of 8.
DSA compiler

Explore the idea visually in the min-heap insertion lab.