Kodewick
Start learning →
Heap sort and top-k27 / 52

Heap sort and top-k

Lesson 27 of 52 · Part 5 · Trees · about 18 minutes

Heap sort builds a max-heap in the array in O(n), then repeatedly swaps the top to the end and sifts down, sorting in O(n log n) with no extra array; for the k largest, the STL has partial_sort and nth_element.

At the end of last lesson, putting everything into a heap and taking it out one by one gave largest first. But that needed a second heap. Heap sort does it in the array itself: first make the vector a heap, then put each largest value taken out at the array's end, using no extra space at all.

Step one: build the heap in place

Pushing one by one costs O(n log n). Faster is bottom-up: leaves are heaps already, so leave them; starting from the last node with children (index n/2 − 1) and going back to the front, sift each node down once. When a node's turn comes, both its subtrees are heaps already, and one sift down makes the whole subtree a heap.

30
11
53
24
62
45
301162532445

Building 3 1 6 5 2 4 into a max-heap in place: from index 2 back to the front, each node sifts down once

Why only O(n): how far a node sifts down depends on how high above the leaves it is, and half the nodes are leaves (0 steps), a quarter are one level up (at most 1 step), and only the root walks log n steps. In total n/4 × 1 + n/8 × 2 + n/16 × 3 + … < n. The STL's make_heap, and building a priority_queue from a range, both build this way.

Guess the outputA wrong guess is fine

Building 1 2 3 4 5 6 7 into a max-heap bottom-up: what does the array become?

1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6void sift_down(vector<int>& a, int n, int i) {7    while (2 * i + 1 < n) {8        int c = 2 * i + 1;9        if (c + 1 < n && a[c + 1] > a[c]) c++;10        if (a[i] >= a[c]) break;11        swap(a[i], a[c]);12        i = c;13    }14}15 16int main() {17    vector<int> a = {1, 2, 3, 4, 5, 6, 7};18    for (int i = 7 / 2 - 1; i >= 0; i--)19        sift_down(a, 7, i);20    for (int x : a)21        cout << x << " ";22    cout << "\n";23    return 0;24}
Choose one

Building a heap bottom up from 10 values: which index is the first one sifted down?

Choose one

How long does building a heap bottom up from n values take?

Exercise 1

Build the heap

sift_down is given. Fill in build: from index n/2 − 1 back to 0, sift each one down once.

It should print
10 5 8 4 1 3
exercise1.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6void sift_down(vector<int>& a, int n, int i) {7    while (2 * i + 1 < n) {8        int c = 2 * i + 1;9        if (c + 1 < n && a[c + 1] > a[c]) c++;10        if (a[i] >= a[c]) break;11        swap(a[i], a[c]);12        i = c;13    }14}15 16void build(vector<int>& a) {17    int n = a.size();18    // from n / 2 - 1 to 019}20 21int main() {22    vector<int> a = {4, 10, 3, 5, 1, 8};23    build(a);24    for (int x : a)25        cout << x << " ";26    cout << "\n";27    return 0;28}
Output
Press Run or Ctrl+Enter

Step two: the top to the end, then sift down

The top is the largest, which belongs last in the sorted array. So a[0] swaps with the last one, the heap shrinks by 1 (the last one is in place now and stays put), and the new root sifts down once. After n − 1 rounds the array is sorted smallest first.

60
51
13
24
42
35
605142132435

Round one: 6 swaps to the end and never moves again; the other 5 sift down into a heap again

sift_down gets one more parameter, n: it sinks only among the first n, so the sorted part at the back isn't in the heap. The vector goes in by reference, so it changes the caller's one.

main.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6// sift a[i] down among the first n7void sift_down(vector<int>& a, int n, int i) {8    while (2 * i + 1 < n) {9        int c = 2 * i + 1;10        if (c + 1 < n && a[c + 1] > a[c]) c++;11        if (a[i] >= a[c]) break;12        swap(a[i], a[c]);13        i = c;14    }15}16 17void heap_sort(vector<int>& a) {18    int n = a.size();19    for (int i = n / 2 - 1; i >= 0; i--)    // build the heap: O(n)20        sift_down(a, n, i);21    for (int end = n - 1; end > 0; end--) {  // n - 1 rounds22        swap(a[0], a[end]);                  // the largest to the end23        sift_down(a, end, 0);                // the other end values sift down24    }25}26 27int main() {28    vector<int> a = {3, 1, 6, 5, 2, 4, 9, 7, 8};29    heap_sort(a);30    for (int x : a)31        cout << x << " ";32    cout << "\n";33    return 0;34}
Output
1 2 3 4 5 6 7 8 9 

Each round's sift down is O(log n), so n rounds are O(n log n), and the same at best and worst: no bad input turns it into O(n²) the way quick sort can go; it uses a few variables, O(1) extra space. The price: it isn't stable. Swaps jump a long way, and two equal values can change order. In practice it usually runs a little slower than quick sort, because it jumps around the array and uses the cache badly.

Guess the outputA wrong guess is fine

The array 9 7 8 3 5 6 is already a max-heap. After the first round of heap sort (top swapped to the end, the first 5 sifted down again), what does the array look like?

1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6void sift_down(vector<int>& a, int n, int i) {7    while (2 * i + 1 < n) {8        int c = 2 * i + 1;9        if (c + 1 < n && a[c + 1] > a[c]) c++;10        if (a[i] >= a[c]) break;11        swap(a[i], a[c]);12        i = c;13    }14}15 16int main() {17    vector<int> a = {9, 7, 8, 3, 5, 6};18    swap(a[0], a[5]);19    sift_down(a, 5, 0);20    for (int x : a)21        cout << x << " ";22    cout << "\n";23    return 0;24}
Choose one

Which of these is true of heap sort?

Fill inTap one to fill a blank; tap a blank to take it back

After each round swaps the top into a[end], the sift down should only cover the values not yet sorted. What goes in the blank?

1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6void sift_down(vector<int>& a, int n, int i) {7    while (2 * i + 1 < n) {8        int c = 2 * i + 1;9        if (c + 1 < n && a[c + 1] > a[c]) c++;10        if (a[i] >= a[c]) break;11        swap(a[i], a[c]);12        i = c;13    }14}15 16void heap_sort(vector<int>& a) {17    int n = a.size();18    for (int i = n / 2 - 1; i >= 0; i--)19        sift_down(a, n, i);20    for (int end = n - 1; end > 0; end--) {21        swap(a[0], a[end]);22        sift_down(a, , 0);23    }24}25 26int main() {27    vector<int> a = {3, 1, 6, 5, 2, 4, 9, 7, 8};28    heap_sort(a);29    for (int x : a)30        cout << x << " ";31    cout << "\n";32    return 0;33}

Top k: keep only k

A million scores, and only the top 10 wanted. Sorting them all is O(n log n). Better is to keep only a min-heap of size k: its top is "the smallest of the k picked so far", the bar to get in. For each new number: above the bar, it replaces the top, which sifts down; not above the bar, it's dropped.

580
911
722
580911722

The top 3 of 58 91 72 66 99 43 87 95 60 77: the top of the heap is the bar, and only bigger values get in
main.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6// a min-heap's sift down: compare with the smaller child7void sift_down_min(vector<int>& h, int n, int i) {8    while (2 * i + 1 < n) {9        int c = 2 * i + 1;10        if (c + 1 < n && h[c + 1] < h[c]) c++;11        if (h[i] <= h[c]) break;12        swap(h[i], h[c]);13        i = c;14    }15}16 17int main() {18    vector<int> a = {58, 91, 72, 66, 99, 43, 87, 95, 60, 77};19    int k = 3;20    vector<int> h(a.begin(), a.begin() + k);            // the first k go in21    for (int i = k / 2 - 1; i >= 0; i--) sift_down_min(h, k, i);22    for (int i = k; i < (int)a.size(); i++)23        if (a[i] > h[0]) {                              // only above the bar gets in24            h[0] = a[i];25            sift_down_min(h, k, 0);26        }27    cout << "The top " << k << ": ";28    for (int x : h)29        cout << x << " ";30    cout << "(bar " << h[0] << ")\n";31    return 0;32}
Output
The top 3: 91 95 99 (bar 91)

Each number does at most one O(log k) sift down: O(n log k) in all, with memory for only k values, so it works even when the data is too big for memory and streams past one item at a time. The surprise: for the k largest, use a min-heap, because the smallest of those picked must be ready to be thrown out.

MethodTimeExtra space
Sort everything, take the first kO(n log n)depends on the sort
A min-heap of size kO(n log k)O(k)
Quickselect (Chapter 7)O(n) on averageO(1), but it changes the array

In exams: "the sequence after building the heap", "the sequence after heap sort's first pass", "which method picks the k largest of n". Heap sort, quick sort, selection sort and Shell sort are all unstable; heap sort and merge sort are the two that are O(n log n) even at worst.

Choose one

To find the smallest 10 of a million values, which heap do you use?

Choose one

Finding the k largest of n values with a min-heap of size k: how long does it take?

With the STL

The STL has heap sort itself: make_heap builds the heap, and sort_heap is those n − 1 rounds of "swap to the end, then sift down". But for everyday sorting use sort: it's introsort, normally quick sort, switching to heap sort when the recursion gets too deep (a bad input showed up), with insertion sort for short stretches, so it's O(n log n) even at worst. Heap sort is its safety net.

Top k has three ready-made ways, each with its use:

main.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5#include <functional>6using namespace std;7 8int main() {9    vector<int> a = {58, 91, 72, 66, 99, 43, 87, 95, 60, 77};10    int k = 3;11 12    // 1. a min-heap of size k: one too many, throw out the smallest13    priority_queue<int, vector<int>, greater<int>> q;14    for (int x : a) {15        q.push(x);16        if ((int)q.size() > k) q.pop();17    }18    cout << "min-heap bar: " << q.top() << "\n";19 20    // 2. partial_sort: only the first k are sorted, the rest in any order21    vector<int> b = a;22    partial_sort(b.begin(), b.begin() + k, b.end(), greater<int>());23    cout << "partial_sort: ";24    for (int i = 0; i < k; i++) cout << b[i] << " ";25    cout << "\n";26 27    // 3. nth_element: the k-th largest lands at index k - 1, nothing before it is smaller (but unsorted)28    vector<int> c = a;29    nth_element(c.begin(), c.begin() + (k - 1), c.end(), greater<int>());30    cout << "k-th largest (k = " << k << "): " << c[k - 1] << "\n";31 32    // heap sort: build a heap, then sort_heap33    vector<int> d = a;34    make_heap(d.begin(), d.end());35    sort_heap(d.begin(), d.end());36    cout << "sort_heap: ";37    for (int x : d) cout << x << " ";38    cout << "\n";39    return 0;40}
Output
min-heap bar: 91
partial_sort: 99 95 91 
k-th largest (k = 3): 91
sort_heap: 43 58 60 66 72 77 87 91 95 99 

partial_sort is the method just shown: the first k become a heap, any later value better than the top swaps in, and at the end those k are sorted, O(n log k). nth_element is quickselect, O(n) on average, but it only promises the k-th is in the right place; the first k are jumbled, so sort them if you need the order.

Written asTimeWhen
sort everythingO(n log n)k is about as big as n
partial_sort(b, b + k, e)O(n log k)the first k, sorted
nth_element(b, b + k - 1, e)O(n) on averageonly the k-th, or the first k in any order
a size-k priority_queueO(n log k), O(k) memorythe data streams past and can't all be kept
make_heap + sort_heapO(n log n), O(1) extra spacerarely used directly; sort is faster

In interviews: "the k-th largest in an array" comes up a lot. Answer the min-heap first, O(n log k), then quickselect, O(n) on average (in C++, nth_element); when the interviewer adds "the data is a stream" or "it doesn't fit in memory", only the heap still works. "What sort is std::sort": introsort, quick sort + heap sort as a safety net + insertion sort.

Exercise 2

The k-th largest

Find the k-th largest with a size-k min-heap: push every number, and when there are more than k, throw out the top (the smallest). After every number has been through, the top is the k-th largest. Fill in the loop.

It should print
5
exercise2.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8    vector<int> a = {3, 2, 1, 5, 6, 4, 9, 7};9    int k = 4;10    priority_queue<int, vector<int>, greater<int>> q;11    for (int x : a) {12        // push it; pop if q.size() is over k13    }14    cout << q.top() << "\n";15    return 0;16}
Output
Press Run or Ctrl+Enter
Choose one

A million numbers, and all you need is which one is the k-th largest; the order of the rest doesn't matter. What is fastest on average?

Choose one

Someone builds an input made to push quicksort to O(n²) and hands it to std::sort. What happens?

Summary

Take-away

Heap sort: build a heap, then swap the top to the end, one by one

  • Build: sift down each from n/2 − 1 back to the front, O(n)
  • Each round swap(a[0], a[end]), then the first end sift down; O(n log n) in all, O(1) extra space, not stable
  • Top k: a size-k min-heap, replace the top only when bigger, O(n log k)
  • STL: partial_sort for the first k sorted; nth_element for just the k-th, O(n) on average; sort is introsort
1for (int i = n / 2 - 1; i >= 0; i--) sift_down(a, n, i);2for (int end = n - 1; end > 0; end--) {3    swap(a[0], a[end]);4    sift_down(a, end, 0);5}