Pop and sift down
After this: Follow a pop and write the array afterwards.
On this page · 8 sections · 4 checks
In the last lesson, a new value went in at the bottom and climbed up. Pop works the other way round: a value starts at the top and moves down.
Pop returns the root, because the root is the smallest value. That leaves a hole at index 0. The tree cannot keep a hole, because it must have no gaps. Removing the first cell of an array would move every other value, so the array should get shorter at its end instead. So the value that fills the hole comes from the end of the array.
One pop, step by step
Take the heap [3, 5, 8].
- Save the root, 3. This is the value pop will return.
- Take the last value, 8, off the end of the array and put it at index 0. The array is
[8, 5]. The hole is gone and the tree has no gaps. But 8 is too big for the top. - Look at the children of index 0. Its only child is 5. 5 is smaller than 8, so swap them. The array is
[5, 8]. - 8 is at index 1 and has no children, so we stop.
Pop returns 3, and the heap is [5, 8]. Both rules hold again.
Two children: take the smaller one
Often a value has two children to choose from. Take the heap [1, 3, 8, 5].
- Save the root, 1.
- Move the last value, 5, to index 0. The array is
[5, 3, 8]. - The children of index 0 are 3 and 8. The smaller is 3, and 3 is smaller than 5, so swap them. The array is
[3, 5, 8]. - 5 is at index 1. Its children would be at indexes 3 and 4, but the array has only three cells. It has no children, so we stop.
The swap must use the smaller child. If 5 swapped with 8 instead, the array would be [8, 3, 5]. Then 8 would sit above 3, and the heap rule would be broken at once.
The three steps of every pop
- Save the root. It is the answer.
- Move the last value of the array to index 0. The array is one cell shorter, and the tree is still complete. The value now at the root is usually too big for the top.
- Swap downward. Look at both children, at 2i + 1 and 2i + 2. If the smaller child is smaller than the value, swap them and carry on from that child's index. Stop when no child is smaller, or when there are no children.
Step 3 has a name: . A value sinks through the tree until it reaches its place.
The code
These two methods go inside the MinHeap class from the last lesson.
def pop(self): smallest = self.items[0] last = self.items.pop() # take the last value: the tree stays complete if self.items: self.items[0] = last # fill the hole at the root from the end self._sift_down(0) return smallest
def _sift_down(self, i): n = len(self.items) while True: left, right = 2 * i + 1, 2 * i + 2 smallest = i if left < n and self.items[left] < self.items[smallest]: smallest = left if right < n and self.items[right] < self.items[smallest]: smallest = right if smallest == i: return # no child is smaller: the heap rule holds self.items[i], self.items[smallest] = self.items[smallest], self.items[i] i = smallest # carry on from the child's cell int pop() { int smallest = items.get(0); int last = items.remove(items.size() - 1); // take the last value: the tree stays complete if (!items.isEmpty()) { items.set(0, last); // fill the hole at the root from the end siftDown(0); } return smallest; }
private void siftDown(int i) { int n = items.size(); while (true) { int left = 2 * i + 1, right = 2 * i + 2; int smallest = i; if (left < n && items.get(left) < items.get(smallest)) smallest = left; if (right < n && items.get(right) < items.get(smallest)) smallest = right; if (smallest == i) return; // no child is smaller: the heap rule holds swap(i, smallest); i = smallest; // carry on from the child's cell } }Here is how to read it.
popsaves the root and takes the last value off the array. If the array is now empty, there was only one value, so there is nothing to move. Otherwise it puts the last value at index 0 and starts the sink from there.- In the sift,
leftandrightare the indexes of the two children. A check such asleft < nmakes sure the child exists. - The sift's
smallestholds the index of the smallest of the three values: the parent and its two children. It starts asi, and it changes if a child is smaller. - If
smallestis stilli, no child is smaller, so the rule holds and the loop stops. Otherwise the two values swap, and the loop carries on from the child's index.
Pop until empty
Start from [1, 3, 8, 5] and pop until the heap is empty.
h = MinHeap()for v in [5, 3, 8, 1]: h.push(v)while h.items: print(h.pop(), h.items)1 [3, 5, 8] 3 [5, 8] 5 [8] 8 []
MinHeap h = new MinHeap();for (int v : new int[] {5, 3, 8, 1}) h.push(v);while (!h.isEmpty()) System.out.println(h.pop() + " " + h);1 [3, 5, 8] 3 [5, 8] 5 [8] 8 []
- Pop 1. As you saw above, 5 moves to the root and swaps with 3, which gives
[3, 5, 8]. - Pop 3. As in the first example, 8 moves to the root and swaps with 5, which gives
[5, 8]. - Pop 5. 8 moves to the root:
[8]. It has no children. - Pop 8. The heap is empty.
The values came out as 1, 3, 5, 8. If you pop everything from a heap, you get the values in sorted order. A later lesson turns this into a way of sorting.
Watch it happen
Pop twice, then peek. Before the first pop, the task asks for a prediction: tap the value that will become the new smallest, then watch the last value sink.
- Pop the minimumPop. 1 leaves. 5, the last value, moves to the root and sinks one step. Watch which child it swaps with.
- Pop the minimum
- Peek
- 01
- 13
- 28
- 35
Push a few values and watch them sift up.
Check yourself
The heap is [2, 4, 7, 6]. Pop. What is the array afterwards?
What does this print?
h = MinHeap()for v in [9, 4, 6, 2, 7]: h.push(v)print(h.pop(), h.pop(), h.pop())print(h.items)MinHeap h = new MinHeap();for (int v : new int[] {9, 4, 6, 2, 7}) h.push(v);System.out.println(h.pop() + " " + h.pop() + " " + h.pop());System.out.println(h);After the root is removed, why does the last value of the array move to the root, and not the smaller child?
Complete pop. The root has been saved and the last value has been taken off the array. Write the line that puts that value at the root.
def pop(self): smallest = self.items[0] last = self.items.pop() if self.items: ______________________ # ← fill the hole at the root self._sift_down(0) return smallest int pop() { int smallest = items.get(0); int last = items.remove(items.size() - 1); if (!items.isEmpty()) { ______________________ // ← fill the hole at the root siftDown(0); } return smallest; }Connect
You can now push and pop by hand. The next lesson counts how much work they take.
- Follow a pop: take the root, move the last value to the root, then swap it with its smaller child while that child is smaller.
- Say why the last value fills the hole: the tree must stay complete.
- Write the array after a pop, and know that popping everything gives sorted order.