Heap sort and top-k
Heap sort builds a max-heap in place, then round after round swaps the top to the end and sifts the new root down, O(n log n) with no extra list; for the k largest of n numbers a min-heap of only k is enough.
A log file has 100 million request records, and your boss only wants the 10 slowest. Reading them all into memory and sorting means holding 100 million numbers and making about 2.7 billion comparisons, when only 10 are needed in the end. Last lesson's heap does two jobs here: sorting, since heap sort is O(n log n) and needs no extra list; and top-k: keep only a min-heap of k numbers while you read, so memory is just k and the comparisons are about n log k. This lesson writes both and counts what they save.
Step 1: build a max-heap in place
To sort smallest to largest, use a max-heap (every node no smaller than its children, the largest at the root). As with last lesson's heapify, start at the last node with children (index n // 2 − 1) and go backwards, sifting each node down once; only "swap with the smaller child" becomes "swap with the larger child".
Build [1, 2, 3, 4, 5, 6, 7] into a max-heap from the bottom up. What does the list look like?
1def sift_down(a, i, n):2 while True:3 big = i4 for c in (2 * i + 1, 2 * i + 2):5 if c < n and a[c] > a[big]:6 big = c7 if big == i:8 return9 a[i], a[big] = a[big], a[i]10 i = big11 12a = [1, 2, 3, 4, 5, 6, 7]13for i in range(len(a) // 2 - 1, -1, -1):14 sift_down(a, i, len(a))15print(a)
Compared with the previous lesson's heapify, which turns a list into a min-heap, what is the only difference when you build a max-heap?
Step 2: swap the top to the end, then sift down
The top of the heap is the largest, and once sorted it belongs at the end. So swap a[0] with the heap's last item, shrink the heap by 1 (that last cell is in place and is never touched again), and sift the new root down once, so the front is a max-heap again. After n − 1 rounds the list is sorted smallest to largest.
1def sift_down(a, i, n): # within the first n, let a[i] sink (max-heap)2 while True:3 big = i4 l, r = 2 * i + 1, 2 * i + 25 if l < n and a[l] > a[big]:6 big = l7 if r < n and a[r] > a[big]:8 big = r9 if big == i:10 return11 a[i], a[big] = a[big], a[i]12 i = big13 14def heap_sort(a):15 n = len(a)16 for i in range(n // 2 - 1, -1, -1): # step 1: build a max-heap17 sift_down(a, i, n)18 print("heap built:", a)19 for end in range(n - 1, 0, -1): # step 2: the top goes to end, the heap shrinks by one20 a[0], a[end] = a[end], a[0]21 sift_down(a, 0, end)22 return a23 24print(heap_sort([3, 1, 6, 5, 2, 4]))25print(heap_sort([5, 5, 1, 9, 0, 3, 7]))
heap built: [6, 5, 4, 1, 2, 3] [1, 2, 3, 4, 5, 6] heap built: [9, 5, 7, 5, 0, 3, 1] [0, 1, 3, 5, 5, 7, 9]
Everything happens by swapping inside the original list, so the extra space is O(1). Building is O(n) and the n − 1 rounds of sifting are O(log n) each: O(n log n) in all, whatever the input looks like, with none of quicksort's O(n²) worst case.
| Heap sort | sorted / list.sort (Timsort) | |
|---|---|---|
| Time | always O(n log n) | O(n log n), close to O(n) on nearly sorted input |
| Extra space | O(1) | O(n) |
| Stable (equal items keep their order) | no | yes |
| Real speed | jumps around the list, rather slow | written in C, much faster |
[9, 7, 8, 3, 5, 6] is already a max-heap. After the first round of heap sort (the top swapped to the end, then a sift down in the first 5), what does the list look like?
1def sift_down(a, i, n):2 while True:3 big = i4 for c in (2 * i + 1, 2 * i + 2):5 if c < n and a[c] > a[big]:6 big = c7 if big == i:8 return9 a[i], a[big] = a[big], a[i]10 i = big11 12a = [9, 7, 8, 3, 5, 6]13a[0], a[5] = a[5], a[0]14sift_down(a, 0, 5)15print(a)
Which of these is true of heap sort?
After each round swaps the top into a[end], the sift down only works on the values that are not sorted yet. What goes in the blank?
1def sift_down(a, i, n):2 while True:3 big = i4 for c in (2 * i + 1, 2 * i + 2):5 if c < n and a[c] > a[big]:6 big = c7 if big == i:8 return9 a[i], a[big] = a[big], a[i]10 i = big11 12def heap_sort(a):13 n = len(a)14 for i in range(n // 2 - 1, -1, -1):15 sift_down(a, i, n)16 for end in range(n - 1, 0, -1):17 a[0], a[end] = a[end], a[0]18 sift_down(a, 0, )19 return a20 21print(heap_sort([3, 1, 6, 5, 2, 4, 9, 7, 8]))
a[end] holds a largest value in its final place, and the heap is only indexes 0 to end − 1: end values. With n or end + 1, the big value just put away is counted back into the heap and sinks to the front again.Write heap sort
✓sift_down is already written (max-heap). Complete heap_sort(a): first build the heap from n // 2 − 1 backwards, then round after round swap a[0] to the end and sift the root down, sorting in place smallest to largest.
[1, 2, 3, 4, 5, 6] [0, 1, 2, 2, 7, 7, 9] [] [1]
1def sift_down(a, i, n):2 while True:3 big = i4 for c in (2 * i + 1, 2 * i + 2):5 if c < n and a[c] > a[big]:6 big = c7 if big == i:8 return9 a[i], a[big] = a[big], a[i]10 i = big11 12def heap_sort(a):13 n = len(a)14 # step 1: build a max-heap15 # step 2: end from n - 1 down to 1: swap a[0] and a[end], sift down within the first end16 return a17 18print(heap_sort([3, 1, 6, 5, 2, 4]))19print(heap_sort([2, 9, 2, 0, 7, 7, 1]))20print(heap_sort([]), heap_sort([1]))
Top-k: keep only k
You want the largest k of n numbers. The obvious way is to sort everything and take the last k, O(n log n). But we only care about k of them: keep a min-heap holding just k numbers, whose top is "the smallest of the k kept so far", that is, the bar to get in.
- While the heap has fewer than k: just add the number.
- Once it is full, a new x larger than the top deserves a place: drop the top and put x in (
heapreplace). - Not larger than the top: it doesn't reach the bar, so one look and it is thrown away, 1 comparison.
sorted(data)[-k:]O(n log n)holds all n, and sorts the ones outside the k tooif x > h[0]: heapreplace(h, x)O(n log k)holds only k; anything below the top leaves after one lookWith hand-written heaps, count the comparisons each way for the 10 largest of 800 numbers:
1cmps = 02 3def less(x, y):4 global cmps5 cmps += 16 return x < y7 8def sift_down(a, i, n, before): # before(x, y): x should sit above y9 while True:10 top = i11 for c in (2 * i + 1, 2 * i + 2):12 if c < n and before(a[c], a[top]):13 top = c14 if top == i:15 return16 a[i], a[top] = a[top], a[i]17 i = top18 19def heap_sort(a): # max-heap: larger sits above20 bigger = lambda x, y: less(y, x)21 n = len(a)22 for i in range(n // 2 - 1, -1, -1):23 sift_down(a, i, n, bigger)24 for end in range(n - 1, 0, -1):25 a[0], a[end] = a[end], a[0]26 sift_down(a, 0, end, bigger)27 return a28 29def top_k(data, k): # min-heap: smaller sits above30 h = []31 for x in data:32 if len(h) < k:33 h.append(x)34 if len(h) == k:35 for i in range(k // 2 - 1, -1, -1):36 sift_down(h, i, k, less)37 elif less(h[0], x): # above the bar: replace the top38 h[0] = x39 sift_down(h, 0, k, less)40 return sorted(h, reverse=True)41 42data = [(i * 7919) % 10007 for i in range(800)]43 44cmps = 045print("sort everything:", heap_sort(data[:])[-10:][::-1], cmps, "comparisons")46cmps = 047print("heap of k: ", top_k(data, 10), cmps, "comparisons")
sort everything: [9997, 9987, 9978, 9968, 9949, 9939, 9930, 9920, 9901, 9891] 13028 comparisons heap of k: [9997, 9987, 9978, 9968, 9949, 9939, 9930, 9920, 9901, 9891] 988 comparisons
The same result, with a gap of more than ten times in comparisons. The more numbers and the smaller k, the bigger the gap; and the heap way doesn't need all the data in memory: it can read a file line by line, comparing as it goes.
A min-heap holding only 3 numbers finds the largest 3. What do the final top and the heap itself print as?
1import heapq2 3h = []4for x in [5, 1, 9, 3, 7, 6]:5 if len(h) < 3:6 heapq.heappush(h, x)7 elif x > h[0]:8 heapq.heapreplace(h, x)9print(h[0], h)
[9, 7, 6] is what a max-heap would look like, and [5, 7, 9] forgets the last number, 6.In interviews: the standard answer to "the k-th largest element in an array" (LeetCode 215) is the min-heap of k, O(n log k), and the top of the heap is the k-th largest. The largest k need a min-heap and the smallest k a max-heap; this counter-intuitive point is often probed: the top is the bar, and you must be able to drop the bar at any time.
To find the smallest 10 of a million values, which heap do you use?
Finding the k largest of n values with a min-heap of size k: how long does it take?
The k-th largest
✓Complete kth_largest(nums, k): with heapq, keep a min-heap holding only k numbers and return the k-th largest. Don't sort the whole list.
5 4 7
1import heapq2 3def kth_largest(nums, k):4 h = []5 # heappush until there are k; after that, heapreplace only when larger than the top6 return None7 8print(kth_largest([3, 2, 1, 5, 6, 4], 2))9print(kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4))10print(kth_largest([7], 1))
How you write it at work
heapq already has top-k: nlargest(k, data) and nsmallest(k, data), which take a key like sorted. For sorting, use sorted or list.sort; don't write heap sort yourself:
1import heapq2 3data = [(i * 7919) % 10007 for i in range(2000)]4print(heapq.nlargest(3, data))5print(heapq.nsmallest(3, data))6 7requests = [("/login", 120), ("/search", 870), ("/home", 35), ("/pay", 640), ("/api", 910)]8slow = heapq.nlargest(2, requests, key=lambda r: r[1])9print(slow)10 11print(sorted(data, reverse=True)[:3] == heapq.nlargest(3, data))12print(max(data), min(data))
[10006, 9997, 9996]
[0, 8, 9]
[('/api', 910), ('/search', 870)]
True
10006 0
- Small k (a few, a few dozen):
heapq.nlargest/nsmallest, a heap of k inside. - k is 1: just
max/min, O(n), the fastest. - k close to n:
sorted(data, reverse=True)[:k]is actually faster. - A huge file or a stream of data: keep your own heap of k, with
heappushandheapreplace, processing as you read.
nsmallest, and nlargest with a key: what does this print?
1import heapq2 3print(heapq.nsmallest(2, [5, 1, 9, 3, 7]), heapq.nlargest(2, ["bb", "a", "ccc"], key=len))
Out of 100,000 numbers you only want the single largest one. What is the fastest way to write it?
max walks through data once, O(n), and it is written in C. nlargest(1, …) is O(n) too but keeps a heap, a little slower; sorted is O(n log n), sorting everything for one value, the most wasteful; a hand-written heap sort is slower still.Summary
Heap sort and top-k
- Heap sort: build a max-heap in place; swap the top to the end, shrink the heap by one, sift the root down; n − 1 rounds
- Always O(n log n), O(1) extra, not stable; at work, sort with sorted anyway
- Top-k: a min-heap of k whose top is the bar; only numbers above the bar get in: O(n log k)
- heapq.nlargest / nsmallest take a key; for k = 1 use max / min
1for end in range(n - 1, 0, -1):2 a[0], a[end] = a[end], a[0]3 sift_down(a, 0, end)4top = heapq.nlargest(k, data, key=f)