---
title: "Heaps and Priority Queues"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 18
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 18 — Heaps 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](#def-b1-heaps-binary-heap) does this inside a plain [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), with no [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-height)). A [dynamic array](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-dynamic-array) grows by doubling, at amortised constant cost ([Chapter 14](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#ch-b1-dynamic-arrays)). A queue serves its elements in order of arrival ([Chapter 15](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#ch-b1-linked-structures)).

## 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](#def-b1-heaps-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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) inserts at its end in $O(1)$, but finding the minimum scans all the elements. An [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) kept sorted, in decreasing order, extracts its last element in $O(1)$, but an insertion shifts elements to make room. For $n$ insertions followed by $n$ extractions, both cost $\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 $n$ random insertions then $n$ extractions: quadratic for the [arrays](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), $n \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](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) of height $h$ is *complete* when its depths $0, \dots, h - 1$ are full (depth $d$ holds $2^d$ nodes) and the nodes at depth $h$ are as far left as possible.

Numbered level by level, from left to right, starting at 0, the nodes of a [complete](#def-b1-heaps-complete) tree fill the indices $0, 1,
\dots, n - 1$ with no gap: the tree can live in an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), and the links are computed instead of stored.

**Proposition 18.3 (Index arithmetic).**

In a [complete binary tree](#def-b1-heaps-complete) numbered from 0, the children of node $i$ are $2i + 1$ and $2i + 2$ (when they are below $n$), and the parent of node $i > 0$ is $\lfloor (i - 1)/2 \rfloor$. A [complete](#def-b1-heaps-complete) tree of $n \geq 1$ nodes has height $\lfloor \log_2 n \rfloor$.

**Proof.** Depth $d$ holds the indices $2^d - 1$ to $2^{d+1} - 2$. Let $i = 2^d - 1 + j$ be the $j$-th node of depth $d$ ($0 \leq j <
2^d$). Its children are the nodes $2j$ and $2j + 1$ of depth $d + 1$, with indices $2^{d+1} - 1 + 2j = 2i + 1$ and $2i +
2$. Conversely, both $2i + 1$ and $2i + 2$ give $\lfloor (k - 1)/2 \rfloor = i$. For the height, see [Exercise 18.9](#exo-b1-heaps-9). ∎

**Definition 18.4 (Binary heap, heap property).**

A *binary heap* is a [complete binary tree](#def-b1-heaps-complete) stored in an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), and the root holds the minimum: find-min costs $O(1)$. A heap is much less ordered than a search tree: siblings are in no particular order, and the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-heaps/fig-286adfefb0fb.svg)

*The min-heap built by [Output 18.2](#out-b1-heaps-demo), as a tree and as the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) is to make it a heap by sifting down every node that has a child, from the last one back to the root.

```c
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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) is a heap except that node $i$ may be smaller than its parent*. If it is not, the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) is a heap except that node $i$ 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)$.

Insertion places the new key as a [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) at the end of the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), which keeps the tree [complete](#def-b1-heaps-complete), and sifts it up. Extraction saves the root, moves the last [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) to the root, and sifts it down.

```c
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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-heaps/fig-1945a48f32d5.svg)

*Extract-min on the heap $[1, 3, 2, 6, 4, 5, 7, 8, 9, 10]$: the last [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), 10, replaces the root 1 (left); it is exchanged with its smaller child 2 (middle), then with 5 (right), where both its [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are empty. Two exchanges, four comparisons.*

## 18.4 Building a heap in linear time

A heap of $n$ given keys can be built by $n$ insertions, at cost $O(n \log n)$; on decreasing keys, each new key climbs to the root, and the cost is $\Theta(n \log n)$. [Heapify](#def-b1-heaps-sift) does better: it sifts down the nodes from the last parent, $\lfloor n/2 \rfloor - 1$, back to the root; when node $i$ is sifted down, both its [subtrees](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) are already heaps (they were treated before it), so it alone may be out of place.

**Proposition 18.6 (Heapify is linear).**

[Heapify](#def-b1-heaps-sift) makes at most $\sum_i h_i < n$ exchanges, where $h_i$ is the height of node $i$.

**Proof.** Sifting node $i$ down makes at most $h_i$ exchanges. A node of height at least $h$ has a descendant $h$ levels below it, on its leftmost path, which is node $(i + 1)2^h - 1$; so the nodes of height at least $h$ are those with $i + 1 \leq
n/2^h$, and there are $\lfloor n/2^h \rfloor$ of them. Each node of height $h_i$ is counted once for each $h = 1, \dots,
h_i$: $\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 - \nu(n)$, where $\nu(n)$ is the number of ones in the binary writing of $n$. On decreasing keys every node goes down to a [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), 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 $n$, top-down growing like $n \log_2 n$.*

| 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 $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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) in increasing order in place: [heapify](#def-b1-heaps-sift) it as a max-heap; then, for $end =
n - 1$ down to 1, exchange the root (the maximum of $a[0..end]$) with $a[end]$, and sift the new root down in $a[0..end)$. The invariant: $a[0..end]$ is a max-heap, and $a[end + 1..n)$ holds the largest keys, sorted, all at least those of the heap.

```c
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](#met-b1-heaps-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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-heaps/fig-cdb17ab5b908.svg)

*[Heapsort](#met-b1-heaps-heapsort) of $[5, 2, 8, 1, 9, 3, 7, 4]$: the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) after [heapify](#def-b1-heaps-sift) 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](#met-b1-heaps-heapsort) of random [arrays](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array): comparisons below $2 n \log_2
n$.*

[Heapsort](#met-b1-heaps-heapsort) runs in $\Theta(n \log n)$ in the worst case and uses $O(1)$ extra memory, which no sort of the previous chapters achieves together; merge sort, of [Chapter 19](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#ch-b1-sorting), needs a second [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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 $k$ selects the $k$ largest of $n$ values in one pass, in $O(n \log k)$ time and $O(k)$ memory: its root is the smallest of the $k$ kept, the one a new value must beat.

```c
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 $k$ longest loans of the town library, with a heap of size $k$ 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](#def-b1-heaps-pq).

In a heap, a smaller key can only move up, by a sift-up from the element’s position, in $O(\log n)$. The difficulty is to find that position: the heap is not a search structure. An *indexed heap* stores the items $0, \dots, m - 1$ and an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) `pos` that every move updates, so that the position of an item is read in $O(1)$. Shortest-path algorithms, in [Chapter 25](https://one-course.com/books/computer-science/3/en/chapter/25-shortest-paths#ch-b1-shortest-paths), 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.

```c
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](#def-b1-heaps-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](#def-b1-heaps-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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-heaps/img-d59cd33d87c6.jpg)

*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](#def-b1-heaps-pq) with [decrease-key](#def-b1-heaps-decrease-key).*

## 18.6 Exercises

**Exercise 18.1 ★.**

Give the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of a min-heap after inserting 5, 3, 8, 1, 4, 2 in this order into an empty heap.

**Solution of Exercise 18.1.**

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

**Exercise 18.2 ★.**

Give the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) after one extract-min on the heap $[1, 3, 2, 5, 4, 8]$.

**Solution of Exercise 18.2.**

The root 1 is returned and the last [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) 8 moves to the root: $[8, 3, 2, 5, 4]$. Its smaller child is 2 (index 2): $[2,
3, 8, 5, 4]$; index 2 has no child in a heap of 5. Result $[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 of Exercise 18.3.**

Parent $\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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) $[2, 5, 3, 9, 6, 4, 8, 10, 7]$ and $[1, 4, 2, 6, 5, 3]$ are min-heaps?

**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.

```c
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]$. Some lines are left out.*

**Solution of Exercise 18.5.**

The first extraction moves 4 to the root of $[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](#def-b1-heaps-binary-heap) 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]$: 4 moves to the root, is exchanged with 3 only, and gives $[3,
4, 2]$, whose root is not the minimum.

**Exercise 18.6 ★★.**

These formulas come from a text that numbers the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) from 1. Explain each wrong line of the output, and correct the formulas.

```c
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]$. Some lines are left out.*

**Solution of Exercise 18.6.**

With 0-based indices, $i/2$ is the parent of $i$ 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 $2i$ point one cell too early (node 1 to node 2, its own sibling). The correct formulas are $\lfloor (i - 1)/2 \rfloor$ and $2i + 1$, or, keeping the 1-based ones, an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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 of Exercise 18.7.**

```c
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 $i$ starts at byte $i \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(n \log k)$ with a heap of size $k$, and test it against sorting.

**Solution of Exercise 18.8.**

```c
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 $k$-th smallest with a heap of size $k$ code/bachelor-1/18-heaps/exercises/kth.c*

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

**Exercise 18.9 ★★.**

Prove that a [complete binary tree](#def-b1-heaps-complete) with $n \geq 1$ nodes has height $\lfloor \log_2 n \rfloor$.

**Solution of Exercise 18.9.**

A [complete](#def-b1-heaps-complete) tree of height $h$ has its depths $0$ to $h - 1$ full, $2^h - 1$ nodes, and between 1 and $2^h$ nodes at depth $h$: $2^h \leq n \leq 2^{h+1} - 1$. So $h \leq \log_2 n < h + 1$, and $h = \lfloor \log_2 n \rfloor$.

**Exercise 18.10 ★★★.**

Prove by induction on $k$ that in a perfect [binary tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-binary-tree) of height $k - 1$, with $n = 2^k - 1$ nodes, the heights of the nodes add up to $n - k$.

**Solution of Exercise 18.10.**

Let $S_k$ be the sum for the perfect tree with $2^k - 1$ nodes. $S_1 = 0 = 1 - 1$. The tree for $k + 1$ is a root of height $k$ above two trees for $k$: $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)$. Test it against sorting.

**Solution of Exercise 18.11.**

```c
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)$. The test compares the median after every addition with a sorted copy.

**Exercise 18.12 ★★★.**

Prove that heapsort makes at most $2n \log_2 n$ key comparisons for $n \geq 2$, and compare with [Output 18.4](#out-b1-heaps-heapsort).

**Solution of Exercise 18.12.**

A sift-down from node $i$ makes at most $h_i$ iterations, each with at most two comparisons. [Heapify](#def-b1-heaps-sift) makes at most $2\sum_i h_i = 2(n - \nu(n)) \leq 2n - 2$ comparisons (problem, Part IV). The extraction for a heap of $e$ elements, $e
= 1, \dots, n - 1$, sifts from the root of a tree of height $\lfloor \log_2 e \rfloor$: at most $2 \sum_{e=1}^{n-1}
\lfloor \log_2 e \rfloor$. With $L = \lfloor \log_2 (n - 1) \rfloor$, the value $j < L$ is taken $2^j$ times and $L$ is taken $n - 2^L$ times, so the sum is $\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 $2^{L+1} \geq n$. In all, at most $2Ln - 2n + 4 + 2n - 2 = 2Ln + 2$ comparisons. Finally $\log_2 n - L
\geq \log_2 \frac{n}{n - 1} \geq \frac{1}{n \ln 2}$, so $2n \log_2 n \geq 2Ln + \frac{2}{\ln 2} > 2Ln + 2$. The measurements give 1.70 to 1.85 times $n \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 $k$ 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 = 378$ returns. A program assigns the returned loans to $k$ branches (by book number modulo $k$), then merges the $k$ 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 $k$ 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 $n$ nodes.*

**Part I — Merging by scanning.**

1. Show that the scanning merge makes at most $(k - 1)n$ comparisons.
2. Compare with the table for $k = 32$ . Why is the count smaller than the bound?
3. Why do both methods make the same number of comparisons for $k = 2$ ?
4. Another method merges the lists two by two, then the results two by two, and so on. What does it cost, for $k$ 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.**

7. State the invariant of the heap during the merge.
8. Prove that the root is the smallest value not yet output.
9. Why is replacing the root and sifting it down better than an extract-min followed by an insertion?
10. Show that each output costs at most $2 \lfloor \log_2 k \rfloor$ comparisons, and bound the total.
11. Compare the bound with the table for $k = 32$ .
12. The program stores $\textit{day} \times 64 + \textit{branch}$ in the heap. Why, and what does it assume about $k$ ?

**Part III — Building the heap.**

13. The merge builds its heap of $k$ heads by $k$ insertions. Would [heapify](#def-b1-heaps-sift) change the total cost noticeably?
14. From [Output 18.3](#out-b1-heaps-build) , give the exchanges per key of the top-down build on decreasing keys, and relate them to $\log_2 n$ .
15. Why do decreasing keys make every node of the bottom-up build sink to a [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) ?
16. Check the bottom-up column against $n - \nu(n)$ for $n = 1023$ and $n = 1\,048\,575$ .
17. Why does each sift-down of [heapify](#def-b1-heaps-sift) make at most two comparisons per exchange, plus two? Bound the comparisons of [heapify](#def-b1-heaps-sift) .
18. [Heapsort](#met-b1-heaps-heapsort) begins with [heapify](#def-b1-heaps-sift) . Which part of heapsort dominates its cost?

**Part IV — The sum of heights.**

19. Show that node $i$ of a heap of $n$ nodes has height $\lfloor \log_2 (n/(i + 1)) \rfloor$ .
20. Deduce that the sum of the heights is $S(n) = \sum_{h \geq 1} \lfloor n/2^h \rfloor$ .
21. Prove that $\sum_{h \geq 1} \lfloor 2^j/2^h \rfloor = 2^j - 1$ , and that $\lfloor n/2^h \rfloor$ is the sum of these quantities over the bits $2^j$ of $n$ .
22. Deduce $S(n) = n - \nu(n)$ , and check it on $n = 1000$ in [Output 18.11](#out-b1-heaps-heights) .
23. How far is $n - \nu(n)$ from the bound $n$ of [Proposition 18.6](#prop-b1-heaps-build) ?
24. State the named result of the problem, *the heap identity* , with what it gives for [heapify](#def-b1-heaps-sift) .

**Solution of Problem 18.1.**

**1.** Each output compares the heads of the non-empty lists, at most $k$ of them: $k - 1$ comparisons, and $(k -
1)n$ in all.

**2.** $31 \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_2 k$ rounds; in each round every element is in one merge, which makes at most one comparison per element output: at most $n \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 $k$ values: lists in files are read as streams, with memory for $k$ 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](#def-b1-heaps-sift) the last [leaf](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree), then [sift up](#def-b1-heaps-sift) the new value: up to twice the work.

**10.** The heap has at most $k$ entries and height at most $\lfloor \log_2 k \rfloor$; a sift-down makes at most two comparisons per level. In all at most $2n \lfloor \log_2 k \rfloor$, plus the $k$ initial insertions.

**11.** $2 \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 \leq 64$ (and days small enough not to overflow an `int`).

**13.** No: $k$ insertions cost $O(k \log k)$, against $O(n \log k)$ for the merge, with $k$ much smaller than $n$.

**14.** 8.01, 10.00, 12.00, …, 18.00 for $n = 2^{10}, 2^{12}, \dots, 2^{20}$ (minus 1): about $\log_2 n - 2$ per key, since half the keys are leaves that climb the whole height, and the average depth is $\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 = 1111111111_2$, $\nu = 10$: $1013$. $1\,048\,575 = 2^{20} - 1$, $\nu = 20$: $1\,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 $s$ exchanges makes at most $2(s + 1)$ comparisons, and [heapify](#def-b1-heaps-sift) at most $2(n - \nu(n)) + 2
\lfloor n/2 \rfloor < 3n$.

**18.** The $n - 1$ extractions, each sifting from the root: $\Theta(n \log n)$ in the worst case, against $O(n)$ for [heapify](#def-b1-heaps-sift).

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

**20.** $h_i \geq h$ exactly when $i + 1 \leq n/2^h$, for $\lfloor n/2^h \rfloor$ nodes; a node of height $h_i$ is counted for $h = 1, \dots, h_i$, so $S(n) = \sum_i h_i = \sum_{h \geq 1} \lfloor n/2^h \rfloor$.

**21.** $\sum_{h=1}^{j} 2^{j-h} = 2^{j-1} + \dots + 1 = 2^j - 1$. Write $n = \sum_j 2^j$ over its bits: $n/2^h$ is $\sum_{j \geq h} 2^{j-h}$, an integer, plus $\sum_{j < h} 2^j/2^h < 1$; so $\lfloor n/2^h \rfloor = \sum_{j \geq h}
2^{j-h} = \sum_j \lfloor 2^j/2^h \rfloor$.

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

**23.** $\nu(n) \leq \lfloor \log_2 n \rfloor + 1$: the bound $n$ is off by at most that much.

**24.** *The heap identity*: in a heap of $n$ nodes the heights add up to $n - \nu(n)$ (questions 19 to 22), checked by program for every $n \leq 10^4$. Hence [heapify](#def-b1-heaps-sift) makes fewer than $n$ exchanges and fewer than $3n$ comparisons, and exactly $n - \nu(n)$ exchanges on decreasing keys, as [Output 18.3](#out-b1-heaps-build) shows.
