Kodewick
Start learning →
Heaps and priority queues24 / 50

Heaps and priority queues

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

A heap keeps a complete binary tree in an array, node i's children at 2 * i + 1 and 2 * i + 2, no parent smaller than its children, so the largest is always at h[0]; insert and remove-top are O(log n), the basis of priority queues.

An emergency room doesn't call patients in the order they came, but the most serious first; an operating system runs the highest-priority task first; a map app always deals next with the junction nearest the start. Each needs a structure where you can put new things in at any time and, at any time, take out the largest (or the smallest). It's called a priority queue, and it's nearly always built as a heap.

A tree stored in an array

A heap is a complete binary tree: every level filled except the last, which fills from the left. A tree like that needs no pointers: put it in an array level by level, left to right, and the indexes are tied together:

  • index i's left child is at 2i + 1, its right child at 2i + 2;
  • index i's parent is at (i − 1) / 2 (integer division).
90
51
13
34
82
65
76
90518213346576

One heap drawn two ways: read the tree level by level, left to right, and you get the array under it; each node shows its index

A max-heap's rule: every node is at least as big as its children (a min-heap the other way round: at most as big). It only cares about parents and children, not brothers: 5 and 8 could be either way round. So a heap isn't sorted; it only promises the largest is on top.

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

h is the max-heap from this step's picture. Pick what goes in the blank to work out where index 1's left child is, so the program prints its two children, 1 3.

1#include <stdio.h>2 3int main(void) {4    int h[] = {9, 5, 8, 1, 3, 6, 7};5    int i = 1;6    int left = ;7    printf("%d %d\n", h[left], h[left + 1]);8    return 0;9}
Choose one

Which of these arrays is a max-heap (indexes from 0)?

Choose one

In a max-heap, where must the smallest value be?

Insert: at the end, then sift up

A new value goes in at the end of the array (the tree's next free place), where it may be bigger than its parent, breaking the rule. So it's compared with its parent and swapped if bigger, all the way up until it isn't bigger than its parent, or it's the root. This is sifting up.

80
51
13
34
72
65
8051721334656

Putting 9 into the max-heap 8 5 7 1 3 6: at the end, then swapped with its parent all the way up to the root
Guess the outputA wrong guess is fine

Put 1 2 3 4 5 into an empty max-heap, in that order. What does the array look like?

1#include <stdio.h>2 3int h[100], n = 0;4 5void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }6 7void push(int v) {8    int i = n++;9    h[i] = v;10    while (i > 0 && h[(i - 1) / 2] < h[i]) {11        swap(&h[(i - 1) / 2], &h[i]);12        i = (i - 1) / 2;13    }14}15 16int main(void) {17    push(1);18    push(2);19    push(3);20    push(4);21    push(5);22    for (int i = 0; i < n; i++)23        printf("%d ", h[i]);24    printf("\n");25    return 0;26}
Choose one

Put 8 into the max-heap 10 7 9 3 6 5 2. What does the array look like now?

Choose one

Put 6 4 9 2 5 into an empty min-heap, in that order. What does the array look like?

Exercise 1

Inserting into a min-heap

Make it a min-heap: sift up while smaller than the parent. Finish the while condition and the swap in push.

It should print
1 4 2 7 6 9
exercise1.c
1#include <stdio.h>2 3int h[100], n = 0;4 5void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }6 7void push(int v) {8    int i = n++;9    h[i] = v;10    // while i > 0 and it's smaller than its parent: swap with the parent, and i becomes the parent's index11}12 13int main(void) {14    int a[] = {7, 4, 9, 1, 6, 2};15    for (int i = 0; i < 6; i++)16        push(a[i]);17    for (int i = 0; i < n; i++)18        printf("%d ", h[i]);19    printf("\n");20    return 0;21}
Output
Press Run or Ctrl+Enter

Removing the top: the last one up, then sift down

Once the root (the largest) is taken, the root is empty. Move the array's last value to the root, and the array is one shorter; that value is most likely too small, so it's compared with the bigger of its two children and swapped if smaller, all the way down until it's bigger than both children, or a leaf. This is sifting down.

90
51
13
34
82
65
76
90518213346576

Removing the top, 9: the last one, 7, moves to the root, then swaps with the bigger child and sinks

Why swap with the bigger child: the one that moves up becomes the other child's parent, and only the bigger one is no smaller than the other.

Choose one

Remove the top of the max-heap 10 8 9 4 7 5 6. What does the array look like afterwards?

Choose one

While sifting down, 7's two children are 5 and 8. What goes wrong if 7 swaps with the smaller one, 5?

Exercise 2

Write sift down

Finish the max-heap's pop: once the last one is at the root, compare it with the bigger child, swap if smaller, all the way down.

It should print
9 8 7 6 5 3 2
exercise2.c
1#include <stdio.h>2 3int h[100] = {9, 6, 8, 2, 5, 7, 3}, n = 7;4 5void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }6 7int pop(void) {8    int top = h[0];9    h[0] = h[--n];10    int i = 0;11    // while there's a left child: c = the left child; c++ if the right is bigger; stop if h[i] >= h[c]; otherwise swap, i = c12    return top;13}14 15int main(void) {16    for (int k = 0; k < 7; k++)17        printf("%d ", pop());18    printf("\n");19    return 0;20}
Output
Press Run or Ctrl+Enter

In C: a priority queue that works

Write sifting up and sifting down as push and pop, and you have a priority queue that works. The whole heap is an array h plus a count n: push puts the value in h[n] and sifts it up; pop takes h[0], moves h[n − 1] up to the root and sifts it down.

main.c
1#include <stdio.h>2 3int h[100], n = 0;4 5void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }6 7void push(int v) {8    int i = n++;9    h[i] = v;10    while (i > 0 && h[(i - 1) / 2] < h[i]) {   // bigger than its parent: sift up11        swap(&h[(i - 1) / 2], &h[i]);12        i = (i - 1) / 2;13    }14}15 16int pop(void) {17    int top = h[0];18    h[0] = h[--n];                              // the last one to the root19    int i = 0;20    while (2 * i + 1 < n) {21        int c = 2 * i + 1;                      // the left child22        if (c + 1 < n && h[c + 1] > h[c]) c++;  // the right child if it's bigger23        if (h[i] >= h[c]) break;24        swap(&h[i], &h[c]);                     // sift down25        i = c;26    }27    return top;28}29 30int main(void) {31    int a[] = {3, 8, 1, 9, 5, 7, 2};32    for (int i = 0; i < 7; i++)33        push(a[i]);34    printf("the heap's array: ");35    for (int i = 0; i < n; i++)36        printf("%d ", h[i]);37    printf("\ntaken out:        ");38    while (n > 0)39        printf("%d ", pop());40    printf("\n");41    return 0;42}
Output
the heap's array: 9 8 7 3 5 1 2 
taken out:        9 8 7 5 3 2 1 

The array itself looks jumbled, but each one taken out is the largest left: take them all and they come out largest to smallest. The next lesson's heap sort is exactly this idea.

OperationTimeWhat it does
See the largestO(1)it's h[0]
InsertO(log n)sift up, at most the height
Remove the topO(log n)sift down, at most the height

Against the alternatives: an unsorted array inserts in O(1) but finds the largest in O(n); a sorted array gives the largest in O(1) but shifts O(n) to insert. A heap does both in O(log n): about twenty steps even for a million values.

In exams: "insert … one by one into an initially empty min-heap and draw the result", "the heap after removing the top", "the children of node i in a complete binary tree". Watch whether the question counts from 0 or from 1: counting from 1, the children are 2i and 2i + 1, the parent i / 2.

Choose one

In the question, the heap is indexed from 1 (the root is h[1]). Where are node i's parent and left child?

Choose one

Put n values in with this step's push, then take them all out one by one with pop. How long does it take altogether?

Summary

Take-away

Heaps: a complete binary tree in an array, the largest at h[0]

  • Children at 2i + 1 and 2i + 2, the parent at (i − 1) / 2
  • Max-heap: no parent smaller than its children; only parents and children, not sorted
  • Insert: at the end, sift up; remove the top: the last one up, sink it past the bigger child
  • Both O(log n); this is what priority queues use
1while (i > 0 && h[(i - 1) / 2] < h[i]) {2    swap(&h[(i - 1) / 2], &h[i]);3    i = (i - 1) / 2;4}