Lesson 10 of 19
Min-heap insertion
In a min-heap, each parent is at most as large as either child. Insert a new number in the next open spot, then swap it upward while its parent is larger.
Repair the path from the new leaf
Read a heap array one level at a time, left to right. The parent of index i is at index floor((i − 1) / 2) for i above zero. Swapping a new value with its larger parent moves the only possible ordering problem up one level.
Work through an example
A heap holds [3, 8, 6, 9] in level order. Where does each value end up when you insert 2?
Step-by-step solution
- Append 2 at index 4, the next open spot in the tree. Its parent is at index 1 and holds 8.
- Swap 2 with 8. The heap array now reads [3, 2, 6, 9, 8], so compare 2 with its new parent, 3.
- Swap once more. The new value has reached the root and the heap reads [2, 3, 6, 9, 8].
JavaScript example
const heap = [3, 8, 6, 9];
heap.push(2);
let child = heap.length - 1;
while (child > 0) {
const parent = Math.floor((child - 1) / 2);
if (heap[parent] <= heap[child]) break;
[heap[parent], heap[child]] = [heap[child], heap[parent]];
child = parent;
}
heap;DSA compiler
Try it yourself
Finish the animation to unlock this question.
A newly inserted 5 has just moved below a parent holding 3. What should happen next?
Related exercise · Min-heap insertion · See this stage of the beginner path