Heaps and priority queues
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).
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.
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}
2 * i is the formula for indexes counted from 1; here they start at 0, so it is one cell off.Which of these arrays is a max-heap (indexes from 0)?
9 5 8 1 3 6 7, 9 ≥ 5 and 8, 5 ≥ 1 and 3, 8 ≥ 6 and 7, so it is a heap. In 9 5 8 6 3 1 7 the 6 at index 3 is bigger than its parent 5; in 8 9 7 … the 9 is bigger than the root 8; in 9 8 7 1 2 9 3 the 9 at index 5 is bigger than its parent 7.In a max-heap, where must the smallest value be?
9 5 8 1 3 6 7 the smallest, 1, is at index 3. To find the minimum you have to look at all the leaves.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.
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}
Put 8 into the max-heap 10 7 9 3 6 5 2. What does the array look like now?
Put 6 4 9 2 5 into an empty min-heap, in that order. What does the array look like?
2 4 5 6 9.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.
1 4 2 7 6 9
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}
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.
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.
Remove the top of the max-heap 10 8 9 4 7 5 6. What does the array look like afterwards?
6 8 9 4 7 5. 6's children are 8 and 9; the bigger is 9, and 6 < 9: swap, 9 8 6 4 7 5. 6 is now at index 2, with only the 5 at index 5 as a child; 6 > 5: stop.While sifting down, 7's two children are 5 and 8. What goes wrong if 7 swaps with the smaller one, 5?
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.
9 8 7 6 5 3 2
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}
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.
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}
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.
| Operation | Time | What it does |
|---|---|---|
| See the largest | O(1) | it's h[0] |
| Insert | O(log n) | sift up, at most the height |
| Remove the top | O(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.
In the question, the heap is indexed from 1 (the root is h[1]). Where are node i's parent and left child?
(i − 1) / 2 and 2i + 1 are the formulas for indexes from 0.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?
push or pop walks at most the height of the tree, O(log n); 2n of them make O(n log n). And they come out largest first: that is heapsort.Summary
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}