Kodewick
Start learning →
Heaps and priority_queue26 / 52

Heaps and priority_queue

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

A heap keeps a complete binary tree in an array with each parent at least as big as its children, so the largest is at index 0; inserting sifts up and removing the top sifts down, both O(log n), and std::priority_queue is one.

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, it's nearly always built as a heap, and in C++ it's std::priority_queue. We'll write one on a vector<int> first, then look at the STL's.

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.

A vector<int> is just right for it: adding a value is push_back, dropping the last one is pop_back, both O(1), and the size looks after itself.

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 <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> h = {9, 5, 8, 1, 3, 6, 7};7    int i = 1;8    int left = ;9    cout << h[left] << " " << h[left + 1] << "\n";10    return 0;11}
Choose one

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

Insert: at the end, then sift up

A new value is push_backed onto the end (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

Putting 1 2 3 4 5 into an empty max-heap one by one: what's the array?

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

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

Exercise 1

Insert into a min-heap

Make it a min-heap: sift up while smaller than the parent. Fill in the while loop in push.

It should print
1 4 2 7 6 9
exercise1.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6vector<int> h;7 8void push(int v) {9    h.push_back(v);10    int i = h.size() - 1;11    // while i > 0 and it's smaller than its parent: swap with the parent, i becomes the parent's index12}13 14int main() {15    for (int x : {7, 4, 9, 1, 6, 2})16        push(x);17    for (int x : h)18        cout << x << " ";19    cout << "\n";20    return 0;21}
Output
Press Run or Ctrl+Enter

Remove the top: move the last one up, sift down

Taking the root (the largest) leaves the root empty. The last value in the array moves to the root, then pop_back; it's probably 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 it's a leaf. This is sifting down.

90
51
13
34
82
65
76
90518213346576

Removing the top 9: the last value 7 moves to the root, then swaps with the bigger child, sinking down

Why swap with the bigger child: the one that comes up becomes the other child's parent, and only the bigger one isn't 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

Fill in the max-heap's pop: once the last value 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.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6vector<int> h = {9, 6, 8, 2, 5, 7, 3};7 8int pop() {9    int top = h[0];10    h[0] = h.back();11    h.pop_back();12    int n = h.size(), i = 0;13    // while there's a left child: c = left child; c++ if the right is bigger; stop if h[i] >= h[c]; otherwise swap, i = c14    return top;15}16 17int main() {18    for (int k = 0; k < 7; k++)19        cout << pop() << " ";20    cout << "\n";21    return 0;22}
Output
Press Run or Ctrl+Enter

In C++: a MaxHeap class

Put sifting up and sifting down together in a small class and you have a priority queue that works. The interface copies the STL's: top() looks at the largest, pop() removes it and returns nothing. The data lives in the vector, with no new, so there's nothing to free by hand.

main.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6class MaxHeap {7    vector<int> h;8public:9    void push(int v) {10        h.push_back(v);11        int i = h.size() - 1;12        while (i > 0 && h[(i - 1) / 2] < h[i]) {     // bigger than its parent: sift up13            swap(h[(i - 1) / 2], h[i]);14            i = (i - 1) / 2;15        }16    }17    void pop() {18        h[0] = h.back();                              // the last one to the root19        h.pop_back();20        int n = h.size(), i = 0;21        while (2 * i + 1 < n) {22            int c = 2 * i + 1;                        // left child23            if (c + 1 < n && h[c + 1] > h[c]) c++;    // the right child if it's bigger24            if (h[i] >= h[c]) break;25            swap(h[i], h[c]);                         // sift down26            i = c;27        }28    }29    int top() const { return h[0]; }30    bool empty() const { return h.empty(); }31    const vector<int>& data() const { return h; }32};33 34int main() {35    MaxHeap q;36    for (int x : {3, 8, 1, 9, 5, 7, 2})37        q.push(x);38    cout << "The heap's array: ";39    for (int x : q.data())40        cout << x << " ";41    cout << "\nTaken out in turn: ";42    while (!q.empty()) {43        cout << q.top() << " ";44        q.pop();45    }46    cout << "\n";47    return 0;48}
Output
The heap's array: 9 8 7 3 5 1 2 
Taken out in turn: 9 8 7 5 3 2 1 

The array itself looks jumbled, but each value taken out is the largest left: take them all and they come out largest first. Next lesson's heap sort is this idea.

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

Against the alternatives: an unsorted array inserts in O(1) but takes O(n) to find the largest; a sorted array hands out the largest in O(1) but takes O(n) shifting to insert. A heap does both in O(log n): about twenty steps even for a million.

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 1: from 1 the children are 2i and 2i + 1 and the parent is 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?

With the STL

std::priority_queue (in <queue>) is a ready-made MaxHeap: a vector inside, push sifts up, pop sifts down. It's a max-heap by default; for a min-heap, the third template argument is greater<int> (in <functional>), and the vector<int> in the middle, the container that holds the values, can't be left out.

main.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8    priority_queue<int> big;                              // max-heap9    priority_queue<int, vector<int>, greater<int>> small; // min-heap10    for (int x : {3, 8, 1, 9, 5}) {11        big.push(x);12        small.push(x);13    }14    cout << "max-heap top: " << big.top() << ", min-heap top: " << small.top() << "\n";15    cout << "max-heap taken out in turn: ";16    while (!big.empty()) {17        cout << big.top() << " ";18        big.pop();                                        // pop returns nothing: top first, then pop19    }20    cout << "\n" << small.size() << " still in the min-heap\n";21    return 0;22}
Output
max-heap top: 9, min-heap top: 1
max-heap taken out in turn: 9 8 5 3 1 
5 still in the min-heap

When the values aren't numbers but things with a priority, you have to say how to compare them. Two ways: give the struct an operator<, or pass a comparator. There's one rule: if the comparator says a < b, a is further from the top. So the default less puts the largest on top, and greater puts the smallest on top.

main.cpp
1#include <iostream>2#include <vector>3#include <string>4#include <queue>5using namespace std;6 7struct Task {8    int pri;        // smaller is more urgent9    int order;      // which one came in when10    string name;11    // "a < b" means a is less urgent than b: a bigger pri is less urgent; the same pri, the later one is12    bool operator<(const Task& o) const {13        if (pri != o.pri) return pri > o.pri;14        return order > o.order;15    }16};17 18int main() {19    priority_queue<Task> q;20    q.push({2, 0, "write the weekly report"});21    q.push({1, 1, "fix the production bug"});22    q.push({2, 2, "answer email"});23    q.push({3, 3, "tidy the desk"});24    while (!q.empty()) {25        cout << q.top().pri << " " << q.top().name << "\n";26        q.pop();27    }28 29    // The same with a lambda: decltype gives the comparator's type, the object goes to the constructor30    auto far = [](int a, int b) { return a % 10 > b % 10; };   // smallest last digit on top31    priority_queue<int, vector<int>, decltype(far)> byDigit(far);32    for (int x : {37, 51, 29, 44})33        byDigit.push(x);34    cout << "by last digit, smallest first: ";35    while (!byDigit.empty()) {36        cout << byDigit.top() << " ";37        byDigit.pop();38    }39    cout << "\n";40    return 0;41}
Output
1 fix the production bug
2 write the weekly report
2 answer email
3 tidy the desk
by last digit, smallest first: 51 44 37 29 

order can't be dropped: a heap isn't stable, so which of two equally urgent tasks comes out first isn't promised. Comparing a rising number as well makes equally urgent ones come out first come, first served. The Huffman tree two lessons on meets this again.

If you don't want a separate container, just to use the vector in your hands as a heap, <algorithm> has a family of functions doing exactly the steps you wrote by hand for MaxHeap:

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> v = {9, 4, 7, 1, 8, 2, 6};8    make_heap(v.begin(), v.end());     // turn it into a max-heap in place, O(n)9    cout << "largest: " << v.front() << "\n";10 11    v.push_back(10);                   // at the end first12    push_heap(v.begin(), v.end());     // then sift up13    cout << "largest after adding 10: " << v.front() << "\n";14 15    pop_heap(v.begin(), v.end());      // the top swaps to the end, the rest sifts down16    cout << "pop_heap put " << v.back() << " at the end\n";17    v.pop_back();                      // really remove it18    cout << "largest now: " << v.front() << ", " << v.size() << " left\n";19    return 0;20}
Output
largest: 9
largest after adding 10: 10
pop_heap put 10 at the end
largest now: 9, 7 left

pop_heap only swaps the top to the end and makes the rest a heap again; it doesn't remove it, so a pop_back follows. They all take greater<int>() for a min-heap too, but every call has to get the same comparator.

Written asTimeNotes
pq.top() / v.front()O(1)the top
pq.push(x) / push_back + push_heapO(log n)sift up
pq.pop() / pop_heap + pop_backO(log n)sift down
make_heap / building a priority_queue from a rangeO(n)bottom-up heap building, next lesson
find any value, change one value's prioritynot offereda heap only knows parents and children; priority_queue won't let you iterate either

Press Visualize on this box and step through it: after each push and pop, pq is drawn as a heap (the Structure view; switch to Cells at the top right to see the vector underneath). You can watch a new number float up from the last slot, and the top go down after a pop:

main.cpp
1#include <iostream>2#include <queue>3using namespace std;4 5int main() {6    priority_queue<int> pq;7    int a[] = {5, 9, 2, 7, 1, 8, 3};8    for (int x : a) pq.push(x);9    pq.pop();10    cout << pq.top() << "\n";11    return 0;12}
Output
8

In interviews: "is priority_queue a max-heap or a min-heap by default" and "how do you write a min-heap" come up almost every time: priority_queue<int, vector<int>, greater<int>>. The comparator's direction is easy to get backwards; remember "if the comparator says a < b, a is lower down". To change a value's priority, the usual move is to push a fresh copy and skip stale ones when they come out (Chapter 5's Dijkstra does that).

Choose one

Which line declares a min-heap (top() is the smallest)?

Guess the outputA wrong guess is fine

Put 6 2 9 4 into a min-heap, pop once, put in 1, then take everything out. What does it print?

1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8    priority_queue<int, vector<int>, greater<int>> q;9    for (int x : {6, 2, 9, 4})10        q.push(x);11    q.pop();12    q.push(1);13    while (!q.empty()) {14        cout << q.top() << " ";15        q.pop();16    }17    cout << "\n";18    return 0;19}

Summary

Take-away

A heap: a complete binary tree in a vector, the largest at h[0]

  • Children 2i + 1 and 2i + 2, parent (i − 1) / 2; only parents and children, not sorted
  • Insert: push_back, sift up; remove the top: the last one up, swapping down with the bigger child; both O(log n)
  • priority_queue is a max-heap by default; a min-heap takes greater<int>; if the comparator says a < b, a is lower down
  • Just using a vector as a heap: make_heap / push_heap / pop_heap
1priority_queue<int> big;2priority_queue<int, vector<int>, greater<int>> small;3big.push(x);4int m = big.top();5big.pop();