Binary heaps: sift up, sift down and heapify
1 The most urgent goes first
An emergency ward does not see patients in the order they arrive. A nurse writes down how many minutes each new patient can safely wait. A free doctor sees the patient with the smallest number next, even one who came in a minute ago.
Six patients are waiting, and they can wait 4, 10, 30, 15, 25 and 40 minutes. All night, patients arrive and doctors take the most urgent one. A plain list is slow at one of the two:
- Unsorted. Adding is O(1), but finding the most urgent reads the whole list, O(n).
- Sorted. The most urgent is at the front, but each new patient is slotted into place, and everyone after them shifts, O(n).
A problem with 10⁵ arrivals and 10⁵ calls for the next patient does around 10¹⁰ steps either way. At about 10⁸ steps a second, that is far past the time limit, so it gets Time Limit Exceeded (TLE).
A heap does both in O(log n) and shows the most urgent in O(1). It keeps just enough order to know who is first.
2 The heap property
The nurse keeps the patients in a tree with one rule: nobody is less urgent than a patient below them. In numbers, each parent is at most its children. This is the heap property, and a tree that keeps it is a min-heap. A max-heap keeps the opposite rule and has the largest on top.
The rule compares a parent only with its own children. Three things follow:
- The smallest value is at the root. Each step up the tree reaches a value that is no larger, and every path up ends at the root.
- Siblings are in no order. 10 and 30 are siblings, and either could be on the left.
- The array is not sorted. 30 sits before 15. But 30 is not above 15 in the tree, so the rule never compares them.
This loose order keeps a heap cheap. Only parents and children are in order, so a change has to fix just one path from the root to a leaf.
A heap is always a complete tree, so it fits in an array with no gaps. As in the trees lesson, the node at index i has its children at 2i + 1 and 2i + 2, and its parent at (i − 1) / 2, rounded down. To stay complete, the array only grows or shrinks at its end.
3 Push: sift up
A new patient arrives who can wait 12 minutes. 12 goes into the next free place, index 6. That makes it a child of 30, and 12 is more urgent than 30. The rule breaks, but only between 12 and its parent.
So 12 climbs: while its parent is larger, the two swap. This is sift up:
A swap breaks nothing below. 30 moves down to a leaf. 40 was at least 30, so it is more than 12 too. Only 12 and its new parent can still be out of order, so the climb goes on until the parent is no larger or 12 is the root.
4 Pop: sift down
A doctor takes the root, 4. To keep the tree complete, the last value, 30, fills the hole at the top, and the array shrinks by one.
30 is not the most urgent, so it sinks. It swaps with its smaller child until both children are larger or it reaches a leaf. This is sift down:
The smaller child matters because it becomes its sibling's parent. At the top, 30 had the children 10 and 12:
If 12 moves up, it sits above 10, and the rule breaks at a place sift down has already left. Only the smaller child can sit above both.
The trace uses the code's names, with each child's value in brackets:
| i | left | right | smallest | heap after |
|---|---|---|---|---|
| 0 | 1 (10) | 2 (12) | 1 | [10, 30, 12, 15, 25, 40] |
| 1 | 3 (15) | 4 (25) | 3 | [10, 15, 12, 30, 25, 40] |
| 3 | 7 (none) | 8 (none) | 3 | no swap: stop |
In the last row, both child indexes are past the end, so 30 is a leaf.
5 The code, and what it costs
The class keeps the array and two helpers. siftUp(i) compares the value at i with its parent, and siftDown(i) with its smaller child. If the two are out of order, the helper swaps them and calls itself on the value's new place. pop and peek return -1 on an empty heap, as the problems ask.
C++
size() is unsigned. siftUp(heap.size() - 1) is safe only because push has just added a value. On an empty vector, size() - 1 wraps around to a huge number.
Compare the list's values with <, never ==. The list holds Integer objects. < compares their values, but == asks whether they are the same object, and that fails for values above 127.
// for the parent. (i - 1) / 2 gives a float such as 2.5, and a list index must be a whole number.
Math.floor for the parent. / keeps the fraction, so (6 - 1) / 2 is 2.5, and heap[2.5] is undefined. JavaScript has no built-in heap, so this is the class to reuse in later problems.
Pointer receivers. Push and Pop change the slice, so every method takes *MinHeap. Go's own container/heap comes in the library section below.
swap_remove(0) takes out index 0 and moves the last value into its place, the same two steps as the other tabs. sift_up checks i == 0 before it works out i - 1, because a usize below 0 panics.
Tuple swap. (heap[i], heap[parent]) = (heap[parent], heap[i]) swaps two places of the list in one line.
Cost. peek reads index 0, so it is O(1). Push and pop swap at most once per level, and a complete tree of n values has about log₂ n levels: 17 for 10⁵. So both are O(log n), and the ward's 10⁵ arrivals and 10⁵ calls take a few million steps. The heap uses only its array, O(n) space.
6 Heapify, and heap sort
When the ward opens, seven patients are already waiting. In order of arrival, they can wait [30, 25, 12, 15, 4, 40, 10] minutes. Instead of seven pushes, heapify turns the array into a heap in place.
One node on its own is already a heap, so the leaves need no work. The last parent is at index n / 2 − 1, here 2. Heapify sifts down every parent from there back to the root. By the time it reaches a parent, both subtrees below are heaps, so one sift down makes the whole subtree a heap.
The loop sits on top of the class's siftDown:
heapify(heap):
n = length of heap
for i from n / 2 - 1 down to 0:
siftDown(i)
Pushing n values one at a time costs O(n log n). Heapify costs only O(n), because most parents sit near the bottom, where a sift down is short. The next lesson proves it.
Heap sort sorts an array in place with a heap. It heapifies the array into a max-heap, so the largest value is at index 0. Then it swaps the root with the last value, shrinks the heap by one, and sifts the new root down. Each round places the next largest value. The n rounds cost O(log n) each, so the sort takes O(n log n) time and O(1) extra space. It is not stable: a long swap can carry a value past an equal one.
7 The library's heap, and pairs
Every language except JavaScript has a heap ready-made, as the standard library lesson showed. The traps are its kind, min or max, and how it orders pairs.
Problems often push pairs, such as a distance and a point's index. In the ward, two patients may both wait 15 minutes, and the one with the smaller id goes first. A pair (minutes, id) compares the minutes, and the ids only on a tie. Here patients 2 and 1 both wait 15 minutes:
C++
A max-heap by default. priority_queue<int> puts the largest on top. greater<…> as the third type makes it a min-heap. A pair compares first, then second.
A min-heap by default. An int[] has no order of its own, so the heap needs the comparator. Use Integer.compare, not a[0] - b[0]: with values near ±10⁹, the subtraction overflows and gives the wrong sign.
A min-heap on a plain list. Tuples compare item by item. For a max-heap, push -minutes and negate it again when it comes out. heapq.heapify(values) is this lesson's heapify, O(n).
No heap. Write the MinHeap above, or sort once when all the values arrive together. Do not compare two arrays with <: it compares them as text, so [4, 7] < [15, 2] is false.
container/heap needs five methods. Less decides the kind: < for a min-heap, > for a max-heap. Call heap.Push and heap.Pop, not the type's own methods. heap.Init is this lesson's heapify.
A max-heap by default. BinaryHeap puts the largest on top, and Reverse turns it into a min-heap. Tuples compare item by item. BinaryHeap::from(vec) heapifies in O(n).
A min-heap on priorities. PriorityQueue<TElement, TPriority> hands back the element with the smallest priority. A tuple priority compares item by item. Equal priorities come out in no fixed order, so the id goes in the tuple.
8 Mistakes, and what the problems need
- Swapping with the larger child. In our pop, 30 swaps with 12. The heap becomes [12, 10, 30, 15, 25, 40], and the next pop returns 12 before 10.
- 1-based index formulas. With the root at index 1, the parent is i / 2. On a 0-based array, pushing our seven values with that parent gives [4, 10, 25, 12, 30, 40, 15], where 25 sits above 15.
- The wrong kind from the library.
priority_queue<int>is a max-heap. Asked for the most urgent patient, a max-heap hands back 40 instead of 4. - Expecting a sorted array. After heapify, our array is [4, 15, 10, 30, 25, 40, 12]. The second smallest, 10, is at index 2. Only repeated pops give the values in order.
The problems in this subtopic need only these pieces:
- Implement a min-heap or a max-heap. This is the class above. For a max-heap, flip each comparison, so sift down picks the larger child.
- Build a heap, or turn a min-heap into a max-heap. Heapify with the right rule, in O(n).
- Check that an array is a min-heap. Compare each parent with its children.
- Heap sort. Heapify into a max-heap, then move the root to the end n times.
Later subtopics use the library heap: the k largest values, simulations that take the best item each step, and two heaps for a running median.
Before writing a sift down, decide which child may move up. In a min-heap it is the smaller one, and in a max-heap the larger one.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.