Kodewick
Start learning →
Heap sort and top k25 / 50

Heap sort and top k

Lesson 25 of 50 · Part 5 · Trees · about 17 minutes

Heap sort first builds a max-heap in the array itself in O(n), then round by round swaps the top, the largest, to the end and sifts the rest down: O(n log n) even at worst, no second array, not stable; a min-heap of size k finds the top k.

At the end of the last lesson, putting everything into a heap and taking it out one by one gave largest to smallest. But that needed a second array for the heap. Heap sort does it in the array itself: first the array is made into a heap, then each largest value taken out goes to the end of the array, with no extra space at all.

Step one: build the heap in place

Pushing one by one is O(n log n). Faster is bottom up: leaves are heaps already, leave them alone; start at the last node that has children (index n/2 − 1) and go backwards, sifting each node down once. When a node's turn comes, its two subtrees are already heaps, and one sift down makes its whole subtree a heap.

30
11
53
24
62
45
301162532445

Making 3 1 6 5 2 4 into a max-heap in place: from index 2 backwards, each node sifted down once

Why only O(n): how far a node sinks depends on how high above the leaves it is, and half the nodes are leaves (0 steps), a quarter just one level up (1 step at most); only the root goes log n steps. All together n/4 × 1 + n/8 × 2 + n/16 × 3 + … < n.

Guess the outputA wrong guess is fine

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

1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5void sift_down(int a[], int n, int i) {6    while (2 * i + 1 < n) {7        int c = 2 * i + 1;8        if (c + 1 < n && a[c + 1] > a[c]) c++;9        if (a[i] >= a[c]) break;10        swap(&a[i], &a[c]);11        i = c;12    }13}14 15int main(void) {16    int a[] = {1, 2, 3, 4, 5, 6, 7};17    for (int i = 7 / 2 - 1; i >= 0; i--)18        sift_down(a, 7, i);19    for (int i = 0; i < 7; i++)20        printf("%d ", a[i]);21    printf("\n");22    return 0;23}
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. Finish build: from index n/2 − 1 back to 0, sift each down once.

It should print
10 5 8 4 1 3
exercise1.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5void sift_down(int a[], int n, int i) {6    while (2 * i + 1 < n) {7        int c = 2 * i + 1;8        if (c + 1 < n && a[c + 1] > a[c]) c++;9        if (a[i] >= a[c]) break;10        swap(&a[i], &a[c]);11        i = c;12    }13}14 15void build(int a[], int n) {16    // from n / 2 - 1 down to 017}18 19int main(void) {20    int a[] = {4, 10, 3, 5, 1, 8};21    build(a, 6);22    for (int i = 0; i < 6; i++)23        printf("%d ", a[i]);24    printf("\n");25    return 0;26}
Output
Press Run or Ctrl+Enter

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

The top is the largest, which in the sorted array belongs last. So swap h[0] with the last one, make the heap one smaller (the last one is in place and never touched again), and sift the new root down once. Repeat n − 1 rounds, and the array is sorted smallest to largest.

60
51
13
24
42
35
605142132435

Round one: 6 goes to the end and never moves again; the other 5 sift back into a heap
main.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5// sift a[i] down, within the first n6void sift_down(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(int a[], int n) {17    for (int i = n / 2 - 1; i >= 0; i--)    // build the heap: O(n)18        sift_down(a, n, i);19    for (int end = n - 1; end > 0; end--) {  // n - 1 rounds20        swap(&a[0], &a[end]);                // the largest to the end21        sift_down(a, end, 0);                // the other end sift down22    }23}24 25int main(void) {26    int a[] = {3, 1, 6, 5, 2, 4, 9, 7, 8};27    heap_sort(a, 9);28    for (int i = 0; i < 9; i++)29        printf("%d ", a[i]);30    printf("\n");31    return 0;32}
Output
1 2 3 4 5 6 7 8 9 

Each round's sift down is O(log n), n rounds is O(n log n), and the same at best and at worst: no bad input turns it into O(n²) as with quicksort; and with just a few variables, the extra space is O(1). The price: not stable, the long-distance swaps can change the order of two equal values. In practice it usually runs a bit slower than quicksort, because jumping around the array makes poor use of the cache.

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 <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5void sift_down(int a[], int n, int i) {6    while (2 * i + 1 < n) {7        int c = 2 * i + 1;8        if (c + 1 < n && a[c + 1] > a[c]) c++;9        if (a[i] >= a[c]) break;10        swap(&a[i], &a[c]);11        i = c;12    }13}14 15int main(void) {16    int a[] = {9, 7, 8, 3, 5, 6};17    swap(&a[0], &a[5]);18    sift_down(a, 5, 0);19    for (int i = 0; i < 6; i++)20        printf("%d ", a[i]);21    printf("\n");22    return 0;23}
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 <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5void sift_down(int a[], int n, int i) {6    while (2 * i + 1 < n) {7        int c = 2 * i + 1;8        if (c + 1 < n && a[c + 1] > a[c]) c++;9        if (a[i] >= a[c]) break;10        swap(&a[i], &a[c]);11        i = c;12    }13}14 15void heap_sort(int a[], int n) {16    for (int i = n / 2 - 1; i >= 0; i--)17        sift_down(a, n, i);18    for (int end = n - 1; end > 0; end--) {19        swap(&a[0], &a[end]);20        sift_down(a, , 0);21    }22}23 24int main(void) {25    int a[] = {3, 1, 6, 5, 2, 4, 9, 7, 8};26    heap_sort(a, 9);27    for (int i = 0; i < 9; i++)28        printf("%d ", a[i]);29    printf("\n");30    return 0;31}

Top k: keep only k

A million scores, and you want only the top 10. Sorting them all is O(n log n). Better is to keep a min-heap of size k: its top is "the smallest of the k chosen so far", the bar to get in. For each new value: above the bar, it replaces the top and sifts down; not above the bar, it's simply 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.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5// a min-heap's sift down: compare with the smaller child6void sift_down_min(int h[], int n, int i) {7    while (2 * i + 1 < n) {8        int c = 2 * i + 1;9        if (c + 1 < n && h[c + 1] < h[c]) c++;10        if (h[i] <= h[c]) break;11        swap(&h[i], &h[c]);12        i = c;13    }14}15 16int main(void) {17    int a[] = {58, 91, 72, 66, 99, 43, 87, 95, 60, 77};18    int k = 3, h[3];19    for (int i = 0; i < k; i++) h[i] = a[i];            // the first k20    for (int i = k / 2 - 1; i >= 0; i--) sift_down_min(h, k, i);21    for (int i = k; i < 10; i++)22        if (a[i] > h[0]) {                              // in only if above the bar23            h[0] = a[i];24            sift_down_min(h, k, 0);25        }26    printf("the top %d: ", k);27    for (int i = 0; i < k; i++)28        printf("%d ", h[i]);29    printf("(the bar: %d)\n", h[0]);30    return 0;31}
Output
the top 3: 91 95 99 (the bar: 91)

Each value costs at most one O(log k) sift down, O(n log k) in all, and the memory is just k slots: it works even when the data is too big for memory and streams past one by one. The surprising part: to find the k largest, use a min-heap, because you must always be ready to throw out the smallest of the chosen.

WayTimeExtra 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 round", "how to choose the k largest of n values". Heap sort, quicksort, selection sort and Shell sort are not stable; heap sort and merge sort are the two that stay 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?

Exercise 2

The k-th largest

Find the k-th largest with a min-heap of size k: once every value has been past, the top is the k-th largest. Finish the loop in main.

It should print
5
exercise2.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5void sift_down_min(int h[], int n, int i) {6    while (2 * i + 1 < n) {7        int c = 2 * i + 1;8        if (c + 1 < n && h[c + 1] < h[c]) c++;9        if (h[i] <= h[c]) break;10        swap(&h[i], &h[c]);11        i = c;12    }13}14 15int main(void) {16    int a[] = {3, 2, 1, 5, 6, 4, 9, 7};17    int n = 8, k = 4, h[4];18    for (int i = 0; i < k; i++) h[i] = a[i];19    for (int i = k / 2 - 1; i >= 0; i--) sift_down_min(h, k, i);20    // the rest: bigger than the top, it replaces the top and sifts down21    printf("%d\n", h[0]);22    return 0;23}
Output
Press Run or Ctrl+Enter

Summary

Take-away

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

  • Build: from n/2 − 1 backwards, sift each down, O(n)
  • Each round swap(a[0], a[end]), then sift down among the first end; O(n log n) in all
  • O(n log n) even at worst, O(1) extra space, not stable
  • Top k: a min-heap of size k, replace the top only when bigger, O(n log k)
1for (i = n / 2 - 1; i >= 0; i--) sift_down(a, n, i);2for (end = n - 1; end > 0; end--) {3    swap(&a[0], &a[end]);4    sift_down(a, end, 0);5}