Push and sift up
After this: Follow a push and say where the new value ends up.
On this page · 8 sections · 3 checks
You know the two rules of a heap: the tree has no gaps, and every parent is less than or equal to its children. Push has to add a value and keep both rules.
Take the heap [3, 5, 8] and push 1. The value 1 is the new smallest, so it has to end up at the root. But the no-gaps rule leaves only one place where the tree can grow: the next free cell at the end of the array. So we put 1 there first, and then we fix the order.
One push, step by step
- Put 1 at the end, at index 3. The array is
[3, 5, 8, 1]. The tree still has no gaps, but the order is wrong. The parent of index 3 is index 1, which holds 5, and 5 is larger than 1. - Swap 1 with its parent. The array is
[3, 1, 8, 5], and 1 is now at index 1. - The parent of index 1 is index 0, which holds 3. 3 is larger than 1, so swap again. The array is
[1, 3, 8, 5]. - 1 is at index 0, the root. It has no parent, so we stop.
That took two swaps, and both rules hold again. The value 8 was never looked at, because it is not on the way up from index 3.
A push can stop early
A new value does not always climb to the root. It stops as soon as its parent is not larger. Here are two more pushes, each starting from [3, 5, 8].
Push 6. Put 6 at index 3: [3, 5, 8, 6]. Its parent holds 5, and 5 ≤ 6. The rule already holds, so we stop. That took no swaps.
Push 4. Put 4 at index 3: [3, 5, 8, 4]. Its parent holds 5, and 5 is larger than 4, so swap: [3, 4, 8, 5]. Its new parent holds 3, and 3 ≤ 4, so we stop. That took one swap.
The two steps of every push
Every push is the same two steps.
- Append the value at the end of the array. The tree stays complete, and the new value is the last leaf.
- Swap upward. Compare the value with its parent at (i − 1) ÷ 2. If the parent is larger, swap them and carry on from the parent's index. Stop when the parent is smaller or equal, or when the value reaches index 0.
Step 2 has a name: . A value rises through the tree until it reaches its place.
A value is only ever compared with its parent. It never looks at a sibling, or at anything off its own line of parents. So a push touches only one path, from a leaf toward the root.
The code
class MinHeap: def __init__(self): self.items = [] # the array that holds the tree
def peek(self): return self.items[0] # the smallest is always at the root: O(1)
def push(self, value): self.items.append(value) # the next free cell: the tree stays complete self._sift_up(len(self.items) - 1)
def _sift_up(self, i): while i > 0: parent = (i - 1) // 2 if self.items[parent] <= self.items[i]: return # the heap rule holds: stop self.items[parent], self.items[i] = self.items[i], self.items[parent] i = parent # carry on from the parent's cellimport java.util.ArrayList;import java.util.List;
public class MinHeap { final List<Integer> items = new ArrayList<>(); // the array that holds the tree
int peek() { return items.get(0); // the smallest is always at the root: O(1) }
void push(int value) { items.add(value); // the next free cell: the tree stays complete siftUp(items.size() - 1); }
private void siftUp(int i) { while (i > 0) { int parent = (i - 1) / 2; if (items.get(parent) <= items.get(i)) return; // the heap rule holds: stop swap(parent, i); i = parent; // carry on from the parent's cell } }
private void swap(int a, int b) { int tmp = items.get(a); items.set(a, items.get(b)); items.set(b, tmp); }
boolean isEmpty() { return items.isEmpty(); }
@Override public String toString() { return items.toString(); }}Here is how to read it.
itemsis the array. The class stores nothing else, so the tree exists only in how we read the indexes.peekreturns the value at index 0.pushappends the value, then starts the climb from the last index.- The highlighted lines are sift up. The loop runs while the value is below the root. It works out the parent's index. If the parent is not larger, it stops. Otherwise it swaps the two values and carries on from the parent's index.
Four pushes in a row
Push 5, 3, 8, 1 into an empty heap and print the array after each one.
h = MinHeap()for v in [5, 3, 8, 1]: h.push(v) print(h.items)print(h.peek())[5] [3, 5] [3, 5, 8] [1, 3, 8, 5] 1
MinHeap h = new MinHeap();for (int v : new int[] {5, 3, 8, 1}) { h.push(v); System.out.println(h);}System.out.println(h.peek());[5] [3, 5] [3, 5, 8] [1, 3, 8, 5] 1
- 5 goes to index 0. It is the root, so it has no parent.
- 3 goes to index 1, under 5. 5 is larger than 3, so they swap:
[3, 5]. - 8 goes to index 2, under 3. 3 ≤ 8, so it stays:
[3, 5, 8]. - 1 goes to index 3, and from here it is the same as the first example above: two swaps give
[1, 3, 8, 5].
Watch it happen
Push the same four values. Before the last push, the task asks for a prediction: tap the index where 1 will settle, then watch it climb.
- Push 5Push 5. It goes to index 0, the root. It has no parent to compare with.
- Push 3
- Push 8
- Push 1
- 0
empty
Push a few values and watch them sift up.
Check yourself
The heap is [3, 5, 8]. Push 1. At which index does 1 end up?
What does this print: the array, then the peek?
h = MinHeap()for v in [6, 2, 7, 4]: h.push(v)print(h.items, h.peek())MinHeap h = new MinHeap();for (int v : new int[] {6, 2, 7, 4}) h.push(v);System.out.println(h + " " + h.peek());Start from an empty heap. Push 4, 7, 2, 9, 1 in that order. What is the array?
Connect
The next lesson does the opposite job: taking the smallest value out.
- Follow a push: add the value at the end, then swap it with its parent while the parent is larger.
- Say where a pushed value ends up by following its line of parents.
- Explain why a push touches only one path from a leaf toward the root.