Why push and pop are fast
After this: Say what each operation costs and why, and how heap sort follows.
On this page · 7 sections · 4 checks
The first lesson promised that push and pop are O(log n). Now you can see why. A push climbs along one path, from the bottom of the tree toward the root. A pop sinks along one path, from the root toward the bottom. So the cost of both depends on one question: how long can a path be?
How tall is a complete tree?
The longest path runs from the root to the bottom level. Its length is the of the tree: the number of levels below the root.
Count the nodes level by level, in a tree whose levels are all full.
| Level | Nodes on this level | Nodes in total so far |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 2 | 3 |
| 2 | 4 | 7 |
| 3 | 8 | 15 |
| 4 | 16 | 31 |
Each level holds twice as many nodes as the level above. So the tree gets wide very fast, and it stays short. Fifteen nodes fit in levels 0 to 3, which is a height of 3. The sixteenth node has to start level 4, which makes the height 4.
Halving, and what log n means
There is a quick way to find the height. Start with the number of nodes. Halve it again and again, rounding down, until you reach 1. The number of halvings is the height.
- 15 → 7 → 3 → 1. That is three halvings, so the height is 3.
- 16 → 8 → 4 → 2 → 1. That is four halvings, so the height is 4.
log₂ n, said "log base 2 of n", counts how many times you can halve n before you reach 1. For most n it is not a whole number, and the height is log₂ n rounded down. Cost notation drops the 2 and writes O(log n).
This matches the parent rule from the heap shape. Going up to a parent roughly halves the index, so the path from index 14 to the root is 14 → 6 → 2 → 0.
Halving reaches 1 very quickly, even from a huge number. A thousand items have height 9, and a million items have height 19.
def height(n): """Levels below the root in a complete tree of n nodes.""" h = 0 while 2 ** (h + 1) - 1 < n: # a full tree of height h holds 2^(h+1) - 1 nodes h += 1 return h
for n in [4, 15, 16, 1000, 1000000]: print(n, height(n))4 2 15 3 16 4 1000 9 1000000 19
public class TreeHeight { /** Levels below the root in a complete tree of n nodes. */ static int height(int n) { int h = 0; while ((1 << (h + 1)) - 1 < n) h++; // a full tree of height h holds 2^(h+1) - 1 nodes return h; }
public static void main(String[] args) { for (int n : new int[] {4, 15, 16, 1000, 1000000}) System.out.println(n + " " + height(n)); }}4 2 15 3 16 4 1000 9 1000000 19
The function raises h until a full tree of height h can hold n nodes. 2 ** (h + 1) - 1(1 << (h + 1)) - 1 is the last column of the table above: 1, 3, 7, 15, 31. In Python, ** raises a number to a power.In Java, 1 << k is a short way to write 2 to the power k.
What each operation costs
Now we can count.
- A push makes at most one swap per level on its way up. That is at most height swaps.
- A pop makes at most one swap per level on its way down, with two comparisons at each level.
- A peek reads index 0.
| Operation | Work | Cost |
|---|---|---|
| Peek | read index 0 | O(1) |
| Push | append, then up to log n swaps | O(log n) |
| Pop | move the last value to the root, then up to log n swaps | O(log n) |
| Find any other value | look through the array | O(n) |
Compare this with the sorted list. The sorted list paid O(n) for each push to keep everything in order. A heap keeps only enough order for the smallest to be at the root, and it pays log n for each change. For a million items, that is about 20 steps in place of a million.
Watch it happen
This heap has fourteen items on four levels. Watch the swaps counter as a value climbs and another one sinks.
- Push 0Push 0 into fourteen items. Watch the swaps counter. How many swaps does a value need to reach the root?
- Pop the minimum
- 01
- 12
- 23
- 34
- 45
- 56
- 67
- 78
- 89
- 910
- 1011
- 1112
- 1213
- 1314
Push a few values and watch them sift up.
Heap sort: a first look
You saw that popping everything gives sorted order. That gives us a way to sort.
- Push all n values into a heap.
- Pop n times. The values come out smallest first.
Each of those 2n operations costs O(log n). The total is written O(n log n), which means n times log n. For a million values that is at most about 2 × 1,000,000 × 20 = 40 million steps. A sort that compares every pair of values would take hundreds of billions of steps. O(n log n) is as good as the best general sorting methods.
values = [5, 3, 8, 1, 9, 2]h = MinHeap()for v in values: h.push(v) # n pushes, each O(log n)sorted_values = []while h.items: sorted_values.append(h.pop()) # n pops, each O(log n): smallest first, every timeprint(sorted_values)[1, 2, 3, 5, 8, 9]
int[] values = {5, 3, 8, 1, 9, 2};MinHeap h = new MinHeap();for (int v : values) h.push(v); // n pushes, each O(log n)List<Integer> sorted = new ArrayList<>();while (!h.isEmpty()) sorted.add(h.pop()); // n pops, each O(log n): smallest first, every timeSystem.out.println(sorted);[1, 2, 3, 5, 8, 9]
Check yourself
For a heap of n items, pick the row with the right costs for peek, push and pop.
A heap holds 1,000 items. At most how many swaps can a single push make?
Sort n numbers by pushing them all into a heap, then popping them all. What does it cost, and why?
What are the two arrays printed?
h = MinHeap()for v in range(1, 8): # 1 to 7 in order: each lands under a smaller parent h.push(v)print(h.items)h.push(0)print(h.items)MinHeap h = new MinHeap();for (int v = 1; v <= 7; v++) h.push(v); // 1 to 7 in order: each lands under a smaller parentSystem.out.println(h);h.push(0);System.out.println(h);Connect
The next lesson leaves our own heap behind and uses the heaps that come with Python and Java.
- Say why a complete tree of n nodes has a height of about log₂ n: 9 for a thousand items, 19 for a million.
- Give the costs: peek O(1), push O(log n), pop O(log n).
- Explain heap sort as n pushes and n pops: O(n log n).