7.1Heap with an Array
Remove the minimum: sift down
A heap exists to hand out the smallest value fast. Reading the root is easy, but removing it leaves a hole at the top of the tree. To fill the hole, the last element is moved to the root and then pushed down until it settles: sift down.
- Why the last element moves to the root when the root is removed
- Why sift down swaps with the smaller of the two children
- Why removing the minimum takes O(log n)
1Idea
The smallest value is in items[0]; that is taken first. The value that will fill the root is the last element, items[count - 1]. Moving it to the root and decreasing count keeps the tree complete, because the cell that empties is at the end of the array.
But the value that reaches the root may be large, and it usually is, since it comes from a leaf. To restore the heap property the value is compared with its children. If one of them is smaller, it swaps with the smaller of the two children and goes down one level. The same check is repeated in its new place.
Why the smaller child? The child that moves up becomes the parent of both children. If the smaller one moves up, it is also smaller than the other child, and the rule holds. Moving the larger child up would leave the smaller one below it, and the rule would break at once.
The loop stops in two cases: the value has no children left (it has reached a leaf), or neither of its children is smaller than it. A node with no left child has no right child either, and a node may have only a left child. That is why the code first checks left < count and right < count for each child.
This operation is the heap version of removing the most urgent element from a priority queue. Called again and again, it returns the values from smallest to largest; heap sort is built on this idea.
2Step by step
The heap in the drawing is 5, 20, 10, 40, 50, 30, 15. We remove the smallest value, 5. i is the index of the value being sifted down, and smallest is the smaller of the two children.
- Start. The heap holds 7 values; the smallest value, 5, is at the root.
removeMin. The heap is not empty. The 5 at the root is copied intovalue; the function will return it at the end.countbecomes 6 and the last element, 15, moves to the root. The tree is complete again, but the root now holds 15 and one of its children, 10, is smaller.- Sift down starts with
i = 0. The children are 20 (index 1) and 10 (index 2). The smaller is 10, sosmallestbecomes 2. Since 10 < 15, a swap is needed. - 15 and 10 swap places. 10 has moved up to the root; 15 is now in cell 2, and
ibecomes 2. - The left child of 15 is 30, in cell 5. Cell 6, which would be its right child, is now beyond
count. 30 is not smaller than 15:smalleststays equal toi, and the loop stops. - The heap is fixed: the new smallest value, 10, is at the root. The function returns the 5 it removed.
#define CAPACITY 15 struct Heap { int items[CAPACITY]; int count;}; void swap(struct Heap* h, int i, int j) { int temp = h->items[i]; h->items[i] = h->items[j]; h->items[j] = temp;} void siftDown(struct Heap* h, int i) { while (true) { int smallest = i; int left = 2 * i + 1, right = 2 * i + 2; if (left < h->count && h->items[left] < h->items[smallest]) smallest = left; if (right < h->count && h->items[right] < h->items[smallest]) smallest = right; if (smallest == i) return; // not larger than either child swap(h, i, smallest); // the smaller child moves up i = smallest; }} bool removeMin(struct Heap* h, int* value) { if (h->count == 0) { return false; // heap is empty } *value = h->items[0]; // the minimum is at the root h->count--; h->items[0] = h->items[h->count]; // the last element to the root siftDown(h, 0); return true;}class ArrayHeap { int[] items; int count = 0; ArrayHeap(int capacity) { items = new int[capacity]; } void swap(int i, int j) { int temp = items[i]; items[i] = items[j]; items[j] = temp; } void siftDown(int i) { while (true) { int smallest = i; int left = 2 * i + 1, right = 2 * i + 2; if (left < count && items[left] < items[smallest]) smallest = left; if (right < count && items[right] < items[smallest]) smallest = right; if (smallest == i) return; // not larger than either child swap(i, smallest); // the smaller child moves up i = smallest; } } int removeMin() { if (count == 0) { throw new IllegalStateException("heap is empty"); } int value = items[0]; // the minimum is at the root count--; items[0] = items[count]; // the last element to the root siftDown(0); return value; }}class ArrayHeap: def __init__(self, capacity): self.items = [None] * capacity self.count = 0 def swap(self, i, j): self.items[i], self.items[j] = self.items[j], self.items[i] def sift_down(self, i): while True: smallest = i left, right = 2 * i + 1, 2 * i + 2 if left < self.count and self.items[left] < self.items[smallest]: smallest = left if right < self.count and self.items[right] < self.items[smallest]: smallest = right if smallest == i: return # not larger than either child self.swap(i, smallest) # the smaller child moves up i = smallest def remove_min(self): if self.count == 0: raise IndexError("heap is empty") value = self.items[0] # the minimum is at the root self.count -= 1 self.items[0] = self.items[self.count] # the last element to the root self.sift_down(0) return valueThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
The value starts at the root and goes down one level per swap; at most the height of the tree, log₂ n swaps. Each level costs two comparisons.
A few variables are enough; the loop is not recursive.
In a priority queue on a sorted array removal was O(1) but insertion was O(n). In a heap both operations are O(log n); for programs that insert and remove a lot, the difference is large.
4Common mistake
A common mistake is swapping only with the left child, or with the first smaller child found:
if (left < h->count && h->items[left] < h->items[i]) { swap(h, i, left); // wrong: the right child may be smaller i = left;}Say 15 has reached the root and its children are 12 and 8. Swapping with the left child moves 12 up to the root; the right child 8 stays smaller than it, and the rule breaks. First find the smaller of the two children, then swap with that one.
5Try it
What does the array become when the smallest value is removed from the heap 2, 6, 4, 9, 7, 5, 8?
The answer is A. The last element, 8, moves to the root: 8, 6, 4, 9, 7, 5. The children are 6 and 4; the smaller is 4, and they swap: 4, 6, 8, 9, 7, 5. 8 is now in cell 2; its only child is the 5 in cell 5, and since 5 < 8 they swap once more: 4, 6, 5, 9, 7, 8.
Show the answer
The answer is A. The last element, 8, moves to the root: 8, 6, 4, 9, 7, 5. The children are 6 and 4; the smaller is 4, and they swap: 4, 6, 8, 9, 7, 5. 8 is now in cell 2; its only child is the 5 in cell 5, and since 5 < 8 they swap once more: 4, 6, 5, 9, 7, 8.
Why does sift down swap with the smaller of the two children?
The answer is A. The child that moves up becomes the parent of the other child. For the rule to hold it must not be larger than that child, and only choosing the smaller child guarantees this. In a heap the smaller child need not be on the left.
Show the answer
The answer is A. The child that moves up becomes the parent of the other child. For the rule to hold it must not be larger than that child, and only choosing the smaller child guarantees this. In a heap the smaller child need not be on the left.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.