कंप्यूटर विज्ञान · किताब 3 · स्नातक वर्ष 1

University Computer Science — Year 1

यह किताब अभी हिन्दी में उपलब्ध नहीं है। संस्करण: 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 O(1)O(1), but finding the minimum scans all the elements. An array kept sorted, in decreasing order, extracts its last element in O(1)O(1), but an insertion shifts elements to make room. For nn insertions followed by nn extractions, both cost Θ(n2)\Theta(n^2):

$ 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
Output 18.1. Comparisons for nn random insertions then nn extractions: quadratic for the arrays, nlog⁡nn \log n for the heap of this chapter.

18.2 The binary heap in an array

Definition 18.2 (Complete binary tree)

A binary tree of height hh is complete when its depths 0,…,h−10, \dots, h - 1 are full (depth dd holds 2d2^d nodes) and the nodes at depth hh 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 0,1,…,n−10, 1, \dots, n - 1 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 ii are 2i+12i + 1 and 2i+22i + 2 (when they are below nn), and the parent of node i>0i > 0 is ⌊(i−1)/2⌋\lfloor (i - 1)/2 \rfloor. A complete tree of n≥1n \geq 1 nodes has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor.

Proof. Depth dd holds the indices 2d−12^d - 1 to 2d+1−22^{d+1} - 2. Let i=2d−1+ji = 2^d - 1 + j be the jj-th node of depth dd (0≤j<2d0 \leq j < 2^d). Its children are the nodes 2j2j and 2j+12j + 1 of depth d+1d + 1, with indices 2d+1−1+2j=2i+12^{d+1} - 1 + 2j = 2i + 1 and 2i+22i + 2. Conversely, both 2i+12i + 1 and 2i+22i + 2 give ⌊(k−1)/2⌋=i\lfloor (k - 1)/2 \rfloor = i. 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 O(1)O(1). 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.

The min-heap built by , as a tree and as the array that stores it. Every key is at most its children’s keys; the arrows are computed from the indices, not stored.
The min-heap built by Output 18.2, as a tree and as the array that stores it. Every key is at most its children’s keys; the arrows are computed from the indices, not stored.

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
    }
}
Listing 18.1. Sifting up and down, with counters code/bachelor-1/18-heaps/listings/heap.c

Each loop keeps an invariant. For sift-up: the array is a heap except that node ii 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 ii 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 O(log⁡n)O(\log n).

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;
}
Listing 18.2. Insertion and extraction code/bachelor-1/18-heaps/listings/heap.c
$ 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]
Output 18.2. The array after each insertion and extraction.
Extract-min on the heap [1, 3, 2, 6, 4, 5, 7, 8, 9, 10]: the last leaf, 10, replaces the root 1 (left); it is exchanged with its smaller child 2 (middle), then with 5 (right), where both its subtrees are empty. Two exchanges, four comparisons.
Extract-min on the heap [1,3,2,6,4,5,7,8,9,10][1, 3, 2, 6, 4, 5, 7, 8, 9, 10]: the last leaf, 10, replaces the root 1 (left); it is exchanged with its smaller child 2 (middle), then with 5 (right), where both its subtrees are empty. Two exchanges, four comparisons.

18.4 Building a heap in linear time

A heap of nn given keys can be built by nn insertions, at cost O(nlog⁡n)O(n \log n); on decreasing keys, each new key climbs to the root, and the cost is Θ(nlog⁡n)\Theta(n \log n). Heapify does better: it sifts down the nodes from the last parent, ⌊n/2⌋−1\lfloor n/2 \rfloor - 1, back to the root; when node ii 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 ∑ihi<n\sum_i h_i < n exchanges, where hih_i is the height of node ii.

Proof. Sifting node ii down makes at most hih_i exchanges. A node of height at least hh has a descendant hh levels below it, on its leftmost path, which is node (i+1)2h−1(i + 1)2^h - 1; so the nodes of height at least hh are those with i+1≤n/2hi + 1 \leq n/2^h, and there are ⌊n/2h⌋\lfloor n/2^h \rfloor of them. Each node of height hih_i is counted once for each h=1,…,hih = 1, \dots, h_i: ∑ihi=∑h≥1⌊n/2h⌋<n(12+14+⋯ )=n\sum_i h_i = \sum_{h \geq 1} \lfloor n/2^h \rfloor < n(\frac12 + \frac14 + \cdots) = n. ∎

The problem shows that the sum is exactly n−ν(n)n - \nu(n), where ν(n)\nu(n) is the number of ones in the binary writing of nn. 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
Output 18.3. Exchanges to build a heap of decreasing keys: bottom-up below nn, top-down growing like nlog⁡2nn \log_2 n.
depth of the nodes (tree of 15 nodes)0123
number of nodes1248
longest sift-down (their height)3210
exchanges at most3440

Most nodes are near the bottom and move little; the few that may move far are near the top. In total 3+4+4=11=15−ν(15)3 + 4 + 4 = 11 = 15 - \nu(15) 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 end=n−1end = n - 1 down to 1, exchange the root (the maximum of a[0..end]a[0..end]) with a[end]a[end], and sift the new root down in a[0..end)a[0..end). The invariant: a[0..end]a[0..end] is a max-heap, and a[end+1..n)a[end + 1..n) 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
    }
}
Listing 18.3. Heapsort code/bachelor-1/18-heaps/listings/heapsort.c
Heapsort of [5, 2, 8, 1, 9, 3, 7, 4]: the array after heapify and after each of the first three extractions. The sorted part grows from the right; the heap part shrinks.
Heapsort of [5,2,8,1,9,3,7,4][5, 2, 8, 1, 9, 3, 7, 4]: the array after heapify and after each of the first three extractions. The sorted part grows from the right; the heap part shrinks.
$ 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
Output 18.4. Heapsort of random arrays: comparisons below 2nlog⁡2n2 n \log_2 n.

Heapsort runs in Θ(nlog⁡n)\Theta(n \log n) in the worst case and uses O(1)O(1) 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)
Output 18.5. Heapsorting patients by urgency: Ben arrived before Finn, but leaves after him.

A heap of size kk selects the kk largest of nn values in one pass, in O(nlog⁡k)O(n \log k) time and O(k)O(k) memory: its root is the smallest of the kk 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;
}
Listing 18.4. The kk longest loans of the town library, with a heap of size kk code/bachelor-1/18-heaps/listings/topk.c
$ 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
Output 18.6. The eight longest returned loans.

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 O(log⁡n)O(\log n). The difficulty is to find that position: the heap is not a search structure. An indexed heap stores the items 0,…,m−10, \dots, m - 1 and an array pos that every move updates, so that the position of an item is read in O(1)O(1). 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
}
Listing 18.5. Sift-up in an indexed heap, and decrease-key code/bachelor-1/18-heaps/listings/iheap.c
$ 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
Output 18.7. An emergency room with decrease-key; urgency 1 is the highest.
At the triage desk of an emergency department, patients are seen by urgency, not by order of arrival, and an urgency can rise while a patient waits: a priority queue with decrease-key.
At the triage desk of an emergency department, patients are seen by urgency, not by order of arrival, and an urgency can rise while a patient waits: a priority queue with decrease-key.

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.

[5][5], [3,5][3, 5], [3,5,8][3, 5, 8]; 1 enters at index 3, climbs past 5 and 3: [1,3,8,5][1, 3, 8, 5]; 4 enters at index 4 below 3 and stays: [1,3,8,5,4][1, 3, 8, 5, 4]; 2 enters at index 5 below 8, climbs once and stops below 1: [1,3,2,5,4,8][1, 3, 2, 5, 4, 8].

Exercise 18.2 ★

Give the array after one extract-min on the heap [1,3,2,5,4,8][1, 3, 2, 5, 4, 8].

Solution

Solution of Exercise 18.2.

The root 1 is returned and the last leaf 8 moves to the root: [8,3,2,5,4][8, 3, 2, 5, 4]. Its smaller child is 2 (index 2): [2,3,8,5,4][2, 3, 8, 5, 4]; index 2 has no child in a heap of 5. Result [2,3,8,5,4][2, 3, 8, 5, 4].

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 ⌊12/2⌋=6\lfloor 12/2 \rfloor = 6, 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 [2,5,3,9,6,4,8,10,7][2, 5, 3, 9, 6, 4, 8, 10, 7] and [1,4,2,6,5,3][1, 4, 2, 6, 5, 3] 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;
    }
}
Listing 18.6. Sift-down with one comparison code/bachelor-1/18-heaps/listings/exo_sift_bug.c
1 4 3 5 6 2 7
Output 18.8. Seven extractions from the heap [1,5,2,6,7,3,4][1, 5, 2, 6, 7, 3, 4]. Some lines are left out.
Solution

Solution of Exercise 18.5.

The first extraction moves 4 to the root of [4,5,2,6,7,3][4, 5, 2, 6, 7, 3]; 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 [1,3,2,4][1, 3, 2, 4]: 4 moves to the root, is exchanged with 3 only, and gives [3,4,2][3, 4, 2], 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; }
Listing 18.7. Parent and left child code/bachelor-1/18-heaps/listings/exo_index_bug.c
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]
Output 18.9. On the heap [1,3,2,7,4][1, 3, 2, 7, 4]. Some lines are left out.
Solution

Solution of Exercise 18.6.

With 0-based indices, i/2i/2 is the parent of ii 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 2i2i point one cell too early (node 1 to node 2, its own sibling). The correct formulas are ⌊(i−1)/2⌋\lfloor (i - 1)/2 \rfloor and 2i+12i + 1, 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);
    }
}
Insertion and extraction of elements of any type code/bachelor-1/18-heaps/exercises/gheap.c

Elements are moved with memcpy, size bytes at a time; the element at index ii starts at byte i⋅sizei \cdot \texttt{size}. 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 O(nlog⁡k)O(n \log k) with a heap of size kk, 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 kk-th smallest with a heap of size kk code/bachelor-1/18-heaps/exercises/kth.c

The heap keeps the kk 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 kk-th smallest. Each value costs O(log⁡k)O(\log k); the test compares with a sorted copy for many nn and kk.

Exercise 18.9 ★★

Prove that a complete binary tree with n≥1n \geq 1 nodes has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor.

Solution

Solution of Exercise 18.9.

A complete tree of height hh has its depths 00 to h−1h - 1 full, 2h−12^h - 1 nodes, and between 1 and 2h2^h nodes at depth hh: 2h≤n≤2h+1−12^h \leq n \leq 2^{h+1} - 1. So h≤log⁡2n<h+1h \leq \log_2 n < h + 1, and h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor.

Exercise 18.10 ★★★

Prove by induction on kk that in a perfect binary tree of height k−1k - 1, with n=2k−1n = 2^k - 1 nodes, the heights of the nodes add up to n−kn - k.

Solution

Solution of Exercise 18.10.

Let SkS_k be the sum for the perfect tree with 2k−12^k - 1 nodes. S1=0=1−1S_1 = 0 = 1 - 1. The tree for k+1k + 1 is a root of height kk above two trees for kk: Sk+1=2Sk+k=2(2k−1−k)+k=2k+1−1−(k+1)S_{k+1} = 2S_k + k = 2(2^k - 1 - k) + k = 2^{k+1} - 1 - (k + 1).

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 O(log⁡n)O(\log n). 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
Adding a number to the two halves code/bachelor-1/18-heaps/exercises/median.c

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, O(log⁡n)O(\log n). The test compares the median after every addition with a sorted copy.

Exercise 18.12 ★★★

Prove that heapsort makes at most 2nlog⁡2n2n \log_2 n key comparisons for n≥2n \geq 2, and compare with Output 18.4.

Solution

Solution of Exercise 18.12.

A sift-down from node ii makes at most hih_i iterations, each with at most two comparisons. Heapify makes at most 2∑ihi=2(n−ν(n))≤2n−22\sum_i h_i = 2(n - \nu(n)) \leq 2n - 2 comparisons (problem, Part IV). The extraction for a heap of ee elements, e=1,…,n−1e = 1, \dots, n - 1, sifts from the root of a tree of height ⌊log⁡2e⌋\lfloor \log_2 e \rfloor: at most 2∑e=1n−1⌊log⁡2e⌋2 \sum_{e=1}^{n-1} \lfloor \log_2 e \rfloor. With L=⌊log⁡2(n−1)⌋L = \lfloor \log_2 (n - 1) \rfloor, the value j<Lj < L is taken 2j2^j times and LL is taken n−2Ln - 2^L times, so the sum is ∑j<Lj2j+L(n−2L)=(L−2)2L+2+Ln−L2L=Ln−2L+1+2≤Ln−n+2\sum_{j < L} j 2^j + L(n - 2^L) = (L - 2)2^L + 2 + Ln - L2^L = Ln - 2^{L+1} + 2 \leq Ln - n + 2, since 2L+1≥n2^{L+1} \geq n. In all, at most 2Ln−2n+4+2n−2=2Ln+22Ln - 2n + 4 + 2n - 2 = 2Ln + 2 comparisons. Finally log⁡2n−L≥log⁡2nn−1≥1nln⁡2\log_2 n - L \geq \log_2 \frac{n}{n - 1} \geq \frac{1}{n \ln 2}, so 2nlog⁡2n≥2Ln+2ln⁡2>2Ln+22n \log_2 n \geq 2Ln + \frac{2}{\ln 2} > 2Ln + 2. The measurements give 1.70 to 1.85 times nlog⁡2nn \log_2 n.

18.7 Problem: Merging the branch libraries’ lists

Problem 18.1

Weekend problem — Merging the branch libraries’ lists

The town library has kk 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 n=378n = 378 returns. A program assigns the returned loans to kk branches (by book number modulo kk), then merges the kk 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
Output 18.10. Merging kk sorted lists of return days.
$ 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
Output 18.11. Sums of heights in heaps of nn nodes.

Part I — Merging by scanning.

  1. Show that the scanning merge makes at most (k−1)n(k - 1)n comparisons.
  2. Compare with the table for k=32k = 32. Why is the count smaller than the bound?
  3. Why do both methods make the same number of comparisons for k=2k = 2?
  4. Another method merges the lists two by two, then the results two by two, and so on. What does it cost, for kk a power of 2?
  5. 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?
  6. Prove that the merged list is sorted, whatever method chooses the smallest head.

Part II — A heap of the heads.

  1. State the invariant of the heap during the merge.
  2. Prove that the root is the smallest value not yet output.
  3. Why is replacing the root and sifting it down better than an extract-min followed by an insertion?
  4. Show that each output costs at most 2⌊log⁡2k⌋2 \lfloor \log_2 k \rfloor comparisons, and bound the total.
  5. Compare the bound with the table for k=32k = 32.
  6. The program stores day×64+branch\textit{day} \times 64 + \textit{branch} in the heap. Why, and what does it assume about kk?

Part III — Building the heap.

  1. The merge builds its heap of kk heads by kk insertions. Would heapify change the total cost noticeably?
  2. From Output 18.3, give the exchanges per key of the top-down build on decreasing keys, and relate them to log⁡2n\log_2 n.
  3. Why do decreasing keys make every node of the bottom-up build sink to a leaf?
  4. Check the bottom-up column against n−ν(n)n - \nu(n) for n=1023n = 1023 and n=1 048 575n = 1\,048\,575.
  5. Why does each sift-down of heapify make at most two comparisons per exchange, plus two? Bound the comparisons of heapify.
  6. Heapsort begins with heapify. Which part of heapsort dominates its cost?

Part IV — The sum of heights.

  1. Show that node ii of a heap of nn nodes has height ⌊log⁡2(n/(i+1))⌋\lfloor \log_2 (n/(i + 1)) \rfloor.
  2. Deduce that the sum of the heights is S(n)=∑h≥1⌊n/2h⌋S(n) = \sum_{h \geq 1} \lfloor n/2^h \rfloor.
  3. Prove that ∑h≥1⌊2j/2h⌋=2j−1\sum_{h \geq 1} \lfloor 2^j/2^h \rfloor = 2^j - 1, and that ⌊n/2h⌋\lfloor n/2^h \rfloor is the sum of these quantities over the bits 2j2^j of nn.
  4. Deduce S(n)=n−ν(n)S(n) = n - \nu(n), and check it on n=1000n = 1000 in Output 18.11.
  5. How far is n−ν(n)n - \nu(n) from the bound nn of Proposition 18.6?
  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 kk of them: k−1k - 1 comparisons, and (k−1)n(k - 1)n in all.

2. 31×378=11 71831 \times 378 = 11\,718 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. log⁡2k\log_2 k rounds; in each round every element is in one merge, which makes at most one comparison per element output: at most nlog⁡2kn \log_2 k comparisons, like the heap.

5. The next output is always one of the heads, so the merge reads each list sequentially and holds kk values: lists in files are read as streams, with memory for kk 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 kk entries and height at most ⌊log⁡2k⌋\lfloor \log_2 k \rfloor; a sift-down makes at most two comparisons per level. In all at most 2n⌊log⁡2k⌋2n \lfloor \log_2 k \rfloor, plus the kk initial insertions.

11. 2×378×5=37802 \times 378 \times 5 = 3780, 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 k≤64k \leq 64 (and days small enough not to overflow an int).

13. No: kk insertions cost O(klog⁡k)O(k \log k), against O(nlog⁡k)O(n \log k) for the merge, with kk much smaller than nn.

14. 8.01, 10.00, 12.00, …, 18.00 for n=210,212,…,220n = 2^{10}, 2^{12}, \dots, 2^{20} (minus 1): about log⁡2n−2\log_2 n - 2 per key, since half the keys are leaves that climb the whole height, and the average depth is log⁡2n−2\log_2 n - 2 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. 1023=111111111121023 = 1111111111_2, ν=10\nu = 10: 10131013. 1 048 575=220−11\,048\,575 = 2^{20} - 1, ν=20\nu = 20: 1 048 5551\,048\,555. 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 ss exchanges makes at most 2(s+1)2(s + 1) comparisons, and heapify at most 2(n−ν(n))+2⌊n/2⌋<3n2(n - \nu(n)) + 2 \lfloor n/2 \rfloor < 3n.

18. The n−1n - 1 extractions, each sifting from the root: Θ(nlog⁡n)\Theta(n \log n) in the worst case, against O(n)O(n) for heapify.

19. The deepest descendants of a node include those on its leftmost path: going dd levels down to the left from node ii reaches node (i+1)2d−1(i + 1)2^d - 1. It exists if and only if (i+1)2d≤n(i + 1)2^d \leq n, so the height is the largest such dd, ⌊log⁡2(n/(i+1))⌋\lfloor \log_2 (n/(i + 1)) \rfloor.

20. hi≥hh_i \geq h exactly when i+1≤n/2hi + 1 \leq n/2^h, for ⌊n/2h⌋\lfloor n/2^h \rfloor nodes; a node of height hih_i is counted for h=1,…,hih = 1, \dots, h_i, so S(n)=∑ihi=∑h≥1⌊n/2h⌋S(n) = \sum_i h_i = \sum_{h \geq 1} \lfloor n/2^h \rfloor.

21. ∑h=1j2j−h=2j−1+⋯+1=2j−1\sum_{h=1}^{j} 2^{j-h} = 2^{j-1} + \dots + 1 = 2^j - 1. Write n=∑j2jn = \sum_j 2^j over its bits: n/2hn/2^h is ∑j≥h2j−h\sum_{j \geq h} 2^{j-h}, an integer, plus ∑j<h2j/2h<1\sum_{j < h} 2^j/2^h < 1; so ⌊n/2h⌋=∑j≥h2j−h=∑j⌊2j/2h⌋\lfloor n/2^h \rfloor = \sum_{j \geq h} 2^{j-h} = \sum_j \lfloor 2^j/2^h \rfloor.

22. Summing over hh: S(n)=∑bits 2j of n(2j−1)=n−ν(n)S(n) = \sum_{\text{bits } 2^j \text{ of } n} (2^j - 1) = n - \nu(n). For n=1000=11111010002n = 1000 = 1111101000_2, ν=6\nu = 6 and S=994S = 994, as printed.

23. ν(n)≤⌊log⁡2n⌋+1\nu(n) \leq \lfloor \log_2 n \rfloor + 1: the bound nn is off by at most that much.

24. The heap identity: in a heap of nn nodes the heights add up to n−ν(n)n - \nu(n) (questions 19 to 22), checked by program for every n≤104n \leq 10^4. Hence heapify makes fewer than nn exchanges and fewer than 3n3n comparisons, and exactly n−ν(n)n - \nu(n) exchanges on decreasing keys, as Output 18.3 shows.

इस अध्याय में परिभाषित शब्द

शब्दावली के सभी 1050 शब्द देखें