यह किताब अभी हिन्दी में उपलब्ध नहीं है। संस्करण: English।
University Computer Science — Year 1 · स्नातक वर्ष 1
18Heaps and Priority Queues
In the waiting room of a hospital’s emergency department, the next patient to be seen is not the one who came first, but the one in the most urgent state. Patients arrive all the time, and a patient’s state can worsen while waiting. A queue serves in order of arrival; this room needs a structure that serves in order of priority, accepts new entries, and changes a priority, each in a few steps however many people wait. The binary heap does this inside a plain array, with no pointer at all, and it also sorts in place and merges sorted lists.
You already know
The depth of a node is its distance from the root, the height of a tree the largest depth (Definition 11.4). A dynamic array grows by doubling, at amortised constant cost (Chapter 14). A queue serves its elements in order of arrival (Chapter 15).
18.1 The priority-queue type
Definition 18.1 (Priority queue)
A priority queue is an abstract type holding elements with keys, called priorities, with the operations insert, find-min (the element of smallest key), extract-min (find it and remove it), and often decrease-key.
A max-priority queue serves the largest key first; exchanging and turns one into the other. Two simple implementations put the cost on one side. An unsorted array inserts at its end in , but finding the minimum scans all the elements. An array kept sorted, in decreasing order, extracts its last element in , but an insertion shifts elements to make room. For insertions followed by extractions, both cost :
$ gcc -std=c17 -O2 -Wall -Wextra -o pq_naive pq_naive.c heap.c -lm && ./pq_naive
n unsorted sorted heap
1000 499500 250676 17228
4000 7998000 4038263 84847
16000 127992000 63644860 404187
64000 2047968000 1024074723 1872136
18.2 The binary heap in an array
Definition 18.2 (Complete binary tree)
A binary tree of height is complete when its depths are full (depth holds nodes) and the nodes at depth are as far left as possible.
Numbered level by level, from left to right, starting at 0, the nodes of a complete tree fill the indices with no gap: the tree can live in an array, and the links are computed instead of stored.
Proposition 18.3 (Index arithmetic)
In a complete binary tree numbered from 0, the children of node are and (when they are below ), and the parent of node is . A complete tree of nodes has height .
Proof. Depth holds the indices to . Let be the -th node of depth (). Its children are the nodes and of depth , with indices and . Conversely, both and give . For the height, see Exercise 18.9. ∎
Definition 18.4 (Binary heap, heap property)
A binary heap is a complete binary tree stored in an array, with the heap property: the key of every node is at most the keys of its children (a min-heap), or at least them (a max-heap).
By transitivity, the key of a node is at most every key of its subtree, and the root holds the minimum: find-min costs . A heap is much less ordered than a search tree: siblings are in no particular order, and the array is not sorted. That is what makes it cheap to maintain.
18.3 Sifting up and down
Definition 18.5 (Sift up, sift down, heapify)
To sift up a node is to exchange it with its parent as long as its key is smaller. To sift down a node is to exchange it with its smaller child as long as that child’s key is smaller. To heapify an array is to make it a heap by sifting down every node that has a child, from the last one back to the root.
void sift_up(int *a, int i) {
while (i > 0) {
int p = (i - 1) / 2;
heap_compares++;
if (a[p] <= a[i]) return; // the heap property holds at i
swap(a, i, p);
i = p; // now only p may be smaller than its parent
}
}
void sift_down(int *a, int n, int i) {
for (;;) {
int c = 2 * i + 1; // the left child
if (c >= n) return;
if (c + 1 < n && (heap_compares++, a[c + 1] < a[c])) c++; // the smaller child
heap_compares++;
if (a[i] <= a[c]) return;
swap(a, i, c);
i = c; // now only c may be larger than its children
}
}
Each loop keeps an invariant. For sift-up: the array is a heap except that node may be smaller than its parent. If it is not, the array is a heap. If it is, the exchange puts the smaller key above both former children of the parent, which were at least the old parent’s key, and only the parent’s position may now be wrong. For sift-down: the array is a heap except that node may be larger than one of its children; exchanging it with the smaller child puts above the other child a key at most that child’s key. Each step moves one level, so both cost .
Insertion places the new key as a leaf at the end of the array, which keeps the tree complete, and sifts it up. Extraction saves the root, moves the last leaf to the root, and sifts it down.
void heap_push(heap *h, int x) {
if (h->n == h->cap) {
h->cap = h->cap ? 2 * h->cap : 8;
h->a = realloc(h->a, (size_t)h->cap * sizeof *h->a);
if (h->a == NULL) exit(1);
}
h->a[h->n] = x; // a new leaf at the end of the last level
sift_up(h->a, h->n++);
}
int heap_min(const heap *h) { return h->a[0]; }
int heap_pop(heap *h) {
int top = h->a[0];
h->a[0] = h->a[--h->n]; // the last leaf moves to the root
sift_down(h->a, h->n, 0);
return top;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o heap_demo heap_demo.c heap.c -lm && ./heap_demo
push 7 [7]
push 4 [4 7]
push 9 [4 7 9]
push 1 [1 4 9 7]
push 8 [1 4 9 7 8]
push 3 [1 4 3 7 8 9]
push 2 [1 4 2 7 8 9 3]
pop -> 1 [2 4 3 7 8 9]
pop -> 2 [3 4 9 7 8]
pop -> 3 [4 7 9 8]
18.4 Building a heap in linear time
A heap of given keys can be built by insertions, at cost ; on decreasing keys, each new key climbs to the root, and the cost is . Heapify does better: it sifts down the nodes from the last parent, , back to the root; when node is sifted down, both its subtrees are already heaps (they were treated before it), so it alone may be out of place.
Proposition 18.6 (Heapify is linear)
Heapify makes at most exchanges, where is the height of node .
Proof. Sifting node down makes at most exchanges. A node of height at least has a descendant levels below it, on its leftmost path, which is node ; so the nodes of height at least are those with , and there are of them. Each node of height is counted once for each : . ∎
The problem shows that the sum is exactly , where is the number of ones in the binary writing of . On decreasing keys every node goes down to a leaf, and the count is reached exactly:
$ gcc -std=c17 -O2 -Wall -Wextra -o build build.c heap.c -lm && ./build
n bottom-up n-v(n) top-down per key
1023 1013 1013 8194 8.01
4095 4083 4083 40962 10.00
16383 16369 16369 196610 12.00
65535 65519 65519 917506 14.00
262143 262125 262125 4194306 16.00
1048575 1048555 1048555 18874370 18.00
| depth of the nodes (tree of 15 nodes) | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| number of nodes | 1 | 2 | 4 | 8 |
| longest sift-down (their height) | 3 | 2 | 1 | 0 |
| exchanges at most | 3 | 4 | 4 | 0 |
Most nodes are near the bottom and move little; the few that may move far are near the top. In total exchanges at most. Insertion one by one has it the other way round: the many leaves may each climb the whole height.
18.5 Heapsort and other uses
Method 18.7 (Heapsort)
Heapsort sorts an array in increasing order in place: heapify it as a max-heap; then, for down to 1, exchange the root (the maximum of ) with , and sift the new root down in . The invariant: is a max-heap, and holds the largest keys, sorted, all at least those of the heap.
void heapsort(int *a, int n) {
for (int i = n / 2 - 1; i >= 0; i--) sift_down_max(a, n, i); // build a max-heap
for (int end = n - 1; end > 0; end--) {
int t = a[0]; // the maximum goes to the end of the heap part
a[0] = a[end], a[end] = t;
sift_down_max(a, end, 0); // a[end..n) is sorted and holds the largest keys
}
}
$ gcc -std=c17 -O2 -Wall -Wextra -o heapsort heapsort.c -lm && ./heapsort
n comparisons / n lg n sorted
1000 16889 1.695 yes
10000 235293 1.771 yes
100000 3018988 1.818 yes
1000000 36793861 1.846 yes
Heapsort runs in in the worst case and uses extra memory, which no sort of the previous chapters achieves together; merge sort, of Chapter 19, needs a second array. It is not stable: elements with equal keys can come out in another order than they came in, since the exchanges move elements across long distances.
$ gcc -std=c17 -O2 -Wall -Wextra -o stability stability.c -lm && ./stability
arrival order: Ana(2) Ben(1) Cleo(2) Dev(3) Eva(2) Finn(1)
heapsorted: Finn(1) Ben(1) Cleo(2) Eva(2) Ana(2) Dev(3)
A heap of size selects the largest of values in one pass, in time and memory: its root is the smallest of the kept, the one a new value must beat.
int main(void) {
read_loans();
int k = 8, returned = 0;
heap h; // its root is the shortest of the k kept: the one to beat
heap_init(&h);
for (int i = 0; i < LOANS; i++) {
if (loans[i].returned < 0) continue;
int days = loans[i].returned - loans[i].out;
returned++;
if (h.n < k) heap_push(&h, days);
else if (days > heap_min(&h)) { // longer than the shortest kept: replace it
h.a[0] = days;
sift_down(h.a, h.n, 0);
}
}
printf("%d returned loans; the %d longest, in days:", returned, k);
while (h.n > 0) printf(" %d", heap_pop(&h));
printf("\n");
heap_free(&h);
return 0;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o topk topk.c heap.c -lm && ./topk
378 returned loans; the 8 longest, in days: 50 50 50 51 51 51 51 51
Definition 18.8 (Decrease-key)
The operation decrease-key lowers the key of an element already in a priority queue.
In a heap, a smaller key can only move up, by a sift-up from the element’s position, in . The difficulty is to find that position: the heap is not a search structure. An indexed heap stores the items and an array pos that every move updates, so that the position of an item is read in . Shortest-path algorithms, in Chapter 25, use it. The alternative, lazy deletion, inserts the element again with its new key and leaves the old entry in the heap, to be skipped when it reaches the root: simpler, at the price of a larger heap.
static void up(iheap *h, int i) {
int x = h->item[i];
while (i > 0 && h->key[h->item[(i - 1) / 2]] > h->key[x]) {
place(h, i, h->item[(i - 1) / 2]); // the parent moves down
i = (i - 1) / 2;
}
place(h, i, x);
}
void ih_decrease(iheap *h, int x, int key) {
h->key[x] = key;
up(h, h->pos[x]); // a smaller key can only move up
}
$ gcc -std=c17 -O2 -Wall -Wextra -o er_demo er_demo.c iheap.c -lm && ./er_demo
next: Ben
Eva's urgency becomes 1; then: Eva Dev Ana Cleo
18.6 Exercises
Exercise 18.1 ★
Give the array of a min-heap after inserting 5, 3, 8, 1, 4, 2 in this order into an empty heap.
Solution
Solution of Exercise 18.1.
, , ; 1 enters at index 3, climbs past 5 and 3: ; 4 enters at index 4 below 3 and stays: ; 2 enters at index 5 below 8, climbs once and stops below 1: .
Exercise 18.2 ★
Give the array after one extract-min on the heap .
Solution
Solution of Exercise 18.2.
The root 1 is returned and the last leaf 8 moves to the root: . Its smaller child is 2 (index 2): ; index 2 has no child in a heap of 5. Result .
Exercise 18.3 ★
In a heap numbered from 0, give the parent, the children and the depth of node 13.
Solution
Solution of Exercise 18.3.
Parent , children 27 and 28. Depth 3 holds the indices 7 to 14, so node 13 is at depth 3.
Exercise 18.4 ★
Which of the arrays and are min-heaps?
Solution
Solution of Exercise 18.4.
The first is not: node 3 holds 9 and its child at index 8 holds 7. The second is: 1 is at most 4 and 2, 4 at most 6 and 5, 2 at most 3.
Exercise 18.5 ★★
This sift-down compares the node with its left child only. Explain the output, and give the smallest heap on which one extraction already goes wrong.
void sift_down(int *a, int n, int i) {
for (int c; (c = 2 * i + 1) < n && a[c] < a[i]; i = c) {
int t = a[i];
a[i] = a[c], a[c] = t;
}
}
1 4 3 5 6 2 7
Solution
Solution of Exercise 18.5.
The first extraction moves 4 to the root of ; the left child 5 is not smaller, so the loop stops, although the right child 2 is. The heap property is broken at the root, and the next extraction returns 4 instead of 2; the errors then pile up, and 2 comes out sixth. Sift-down must choose the smaller of the two children. The smallest heap that goes wrong in one extraction is : 4 moves to the root, is exchanged with 3 only, and gives , whose root is not the minimum.
Exercise 18.6 ★★
These formulas come from a text that numbers the array from 1. Explain each wrong line of the output, and correct the formulas.
int parent(int i) { return i / 2; }
int left(int i) { return 2 * i; }
a[0] = 1: parent a[0] = 1, left child a[0]
a[1] = 3: parent a[0] = 1, left child a[2]
a[2] = 2: parent a[1] = 3, left child a[4]
a[3] = 7: parent a[1] = 3, left child a[6]
a[4] = 4: parent a[2] = 2, left child a[8]
Solution
Solution of Exercise 18.6.
With 0-based indices, is the parent of only by chance. Node 0 is its own parent and its own left child. Node 2 is told that its parent is node 1 (key 3), which looks like a broken heap, but its parent is node 0. Node 4’s parent is node 1, not node 2. The left children point one cell too early (node 1 to node 2, its own sibling). The correct formulas are and , or, keeping the 1-based ones, an array whose cell 0 is unused.
Exercise 18.7 ★★
Write a max-heap whose elements are of any type, given by their size in bytes and a comparison function as for qsort, and test it on numbers and on structures.
Solution
Solution of Exercise 18.7.
void gheap_push(gheap *h, const void *x) {
if (h->n == h->cap) {
h->cap = h->cap ? 2 * h->cap : 8;
h->a = realloc(h->a, h->cap * h->size);
if (h->a == NULL) exit(1);
}
memcpy(at(h, h->n), x, h->size);
for (size_t i = h->n++; i > 0 && h->cmp(at(h, (i - 1) / 2), at(h, i)) < 0; i = (i - 1) / 2)
swap(h, i, (i - 1) / 2);
}
void gheap_pop(gheap *h, void *out) { // the largest element, copied to out; n > 0
memcpy(out, at(h, 0), h->size);
memcpy(at(h, 0), at(h, --h->n), h->size);
for (size_t i = 0, c; (c = 2 * i + 1) < h->n; i = c) {
if (c + 1 < h->n && h->cmp(at(h, c + 1), at(h, c)) > 0) c++;
if (h->cmp(at(h, i), at(h, c)) >= 0) break;
swap(h, i, c);
}
}
Elements are moved with memcpy, size bytes at a time; the element at index starts at byte . The comparison function returns a negative, zero or positive number, as for qsort; reversing it turns the max-heap into a min-heap, which the test uses to serve the most urgent patient first.
Exercise 18.8 ★★
Write kth_smallest(xs, n, k) in time with a heap of size , and test it against sorting.
Solution
Solution of Exercise 18.8.
int kth_smallest(const int *xs, int n, int k) { // 1 <= k <= n
heap h; // negated values: its root is minus the largest of the k kept
heap_init(&h);
for (int i = 0; i < n; i++)
if (h.n < k) heap_push(&h, -xs[i]);
else if (xs[i] < -heap_min(&h)) {
h.a[0] = -xs[i];
sift_down(h.a, h.n, 0);
}
int answer = -heap_min(&h);
heap_free(&h);
return answer;
}
The heap keeps the smallest values seen so far, negated, so that its root is the largest of them. A new value smaller than that root replaces it. At the end the root is the -th smallest. Each value costs ; the test compares with a sorted copy for many and .
Exercise 18.9 ★★
Prove that a complete binary tree with nodes has height .
Solution
Solution of Exercise 18.9.
A complete tree of height has its depths to full, nodes, and between 1 and nodes at depth : . So , and .
Exercise 18.10 ★★★
Prove by induction on that in a perfect binary tree of height , with nodes, the heights of the nodes add up to .
Solution
Solution of Exercise 18.10.
Let be the sum for the perfect tree with nodes. . The tree for is a root of height above two trees for : .
Exercise 18.11 ★★★
Maintain the median of a stream of numbers with two heaps, a max-heap of the lower half and a min-heap of the upper half, so that each new number costs . Test it against sorting.
Solution
Solution of Exercise 18.11.
void median_add(median *m, int x) {
if (m->low.n == 0 || x <= -heap_min(&m->low)) heap_push(&m->low, -x);
else heap_push(&m->high, x);
if (m->low.n > m->high.n + 1) heap_push(&m->high, -heap_pop(&m->low)); // rebalance
else if (m->high.n > m->low.n) heap_push(&m->low, -heap_pop(&m->high));
}
int median_get(const median *m) { return -heap_min(&m->low); } // the lower median
Invariant: every value of the lower heap is at most every value of the upper heap, and the lower heap has as many elements as the upper one or one more. Its root is then the lower median. A new value goes to the side its value belongs to; if the sizes then differ by two, one root moves to the other heap, which keeps both properties. Each addition makes at most three heap operations, . The test compares the median after every addition with a sorted copy.
Exercise 18.12 ★★★
Prove that heapsort makes at most key comparisons for , and compare with Output 18.4.
Solution
Solution of Exercise 18.12.
A sift-down from node makes at most iterations, each with at most two comparisons. Heapify makes at most comparisons (problem, Part IV). The extraction for a heap of elements, , sifts from the root of a tree of height : at most . With , the value is taken times and is taken times, so the sum is , since . In all, at most comparisons. Finally , so . The measurements give 1.70 to 1.85 times .
18.7 Problem: Merging the branch libraries’ lists
Problem 18.1
Weekend problem — Merging the branch libraries’ lists
The town library has branches; each keeps the list of the loans returned to it, sorted by day of return, and the town wants one sorted list of all returns. A program assigns the returned loans to branches (by book number modulo ), then merges the sorted lists in two ways: by comparing the heads of all the lists at each step, and with a min-heap that holds the head of each list. It counts the comparisons and checks the merged list.
$ gcc -std=c17 -O2 -Wall -Wextra -o kmerge kmerge.c heap.c -lm && ./kmerge
k n scanning heap sorted
2 378 377 377 yes
4 378 1127 934 yes
8 378 2572 1487 yes
16 378 5420 2104 yes
32 378 10884 2720 yes
$ python heights_sum.py
n sum of heights n - v(n)
1 0 0
2 1 1
3 1 1
7 4 4
10 8 8
100 97 97
1000 994 994
1023 1013 1013
1024 1023 1023
10000 9995 9995
n <= 10000 where they differ: none
Part I — Merging by scanning.
- Show that the scanning merge makes at most comparisons.
- Compare with the table for . Why is the count smaller than the bound?
- Why do both methods make the same number of comparisons for ?
- Another method merges the lists two by two, then the results two by two, and so on. What does it cost, for a power of 2?
- Why does the merge need only one value from each list at a time, and why does that matter for long lists stored in files?
- Prove that the merged list is sorted, whatever method chooses the smallest head.
Part II — A heap of the heads.
- State the invariant of the heap during the merge.
- Prove that the root is the smallest value not yet output.
- Why is replacing the root and sifting it down better than an extract-min followed by an insertion?
- Show that each output costs at most comparisons, and bound the total.
- Compare the bound with the table for .
- The program stores in the heap. Why, and what does it assume about ?
Part III — Building the heap.
- The merge builds its heap of heads by insertions. Would heapify change the total cost noticeably?
- From Output 18.3, give the exchanges per key of the top-down build on decreasing keys, and relate them to .
- Why do decreasing keys make every node of the bottom-up build sink to a leaf?
- Check the bottom-up column against for and .
- Why does each sift-down of heapify make at most two comparisons per exchange, plus two? Bound the comparisons of heapify.
- Heapsort begins with heapify. Which part of heapsort dominates its cost?
Part IV — The sum of heights.
- Show that node of a heap of nodes has height .
- Deduce that the sum of the heights is .
- Prove that , and that is the sum of these quantities over the bits of .
- Deduce , and check it on in Output 18.11.
- How far is from the bound of Proposition 18.6?
- State the named result of the problem, the heap identity, with what it gives for heapify.
Solution
Solution of Problem 18.1.
1. Each output compares the heads of the non-empty lists, at most of them: comparisons, and in all.
2. against 10 884: towards the end lists run out, and fewer heads are compared.
3. With two lists both methods make one comparison per output while both lists last, and none after.
4. rounds; in each round every element is in one merge, which makes at most one comparison per element output: at most comparisons, like the heap.
5. The next output is always one of the heads, so the merge reads each list sequentially and holds values: lists in files are read as streams, with memory for values only.
6. Each list is sorted, so every value not yet output is at least the head of its list, hence at least the smallest head, which is the value output. So the outputs never decrease.
7. The heap holds exactly one entry for each non-empty list: the current head of that list.
8. The root is the smallest entry, the smallest head, which by question 6 is the smallest value not yet output.
9. The next head of the same list takes the root’s place and is sifted down once. Extract-min followed by an insertion would sift down the last leaf, then sift up the new value: up to twice the work.
10. The heap has at most entries and height at most ; a sift-down makes at most two comparisons per level. In all at most , plus the initial insertions.
11. , and the table shows 2720, including the insertions.
12. The integer orders first by day, then by branch: the entries are distinct and the order of equal days is fixed, and the branch is recovered by % 64. It assumes (and days small enough not to overflow an int).
13. No: insertions cost , against for the merge, with much smaller than .
14. 8.01, 10.00, 12.00, …, 18.00 for (minus 1): about per key, since half the keys are leaves that climb the whole height, and the average depth is or so.
15. A node’s key is larger than all the keys below it, so at each step it is larger than its smaller child and goes down, until it has no child.
16. , : . , : . Both match.
17. Each iteration compares the two children, then the node with the smaller one; an exchange follows, or the sift stops. So a sift of exchanges makes at most comparisons, and heapify at most .
18. The extractions, each sifting from the root: in the worst case, against for heapify.
19. The deepest descendants of a node include those on its leftmost path: going levels down to the left from node reaches node . It exists if and only if , so the height is the largest such , .
20. exactly when , for nodes; a node of height is counted for , so .
21. . Write over its bits: is , an integer, plus ; so .
22. Summing over : . For , and , as printed.
23. : the bound is off by at most that much.
24. The heap identity: in a heap of nodes the heights add up to (questions 19 to 22), checked by program for every . Hence heapify makes fewer than exchanges and fewer than comparisons, and exactly exchanges on decreasing keys, as Output 18.3 shows.