TExcelTAD

Exercises

Fifteen problems covering the whole course: heaps, quicksort, lower bounds, linear-time sorting and selection. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result by counting, which you can edit and run.

Tip: For a bound or a count, test the smallest cases by hand before you generalise, and for a trace, write down the array after every step. Most mistakes in these exercises are off-by-one errors in indices, which a trace exposes at once.

# Exercise Practises
1 Where can the third largest be? the heap property
2 Build a heap by hand bottom-up construction
3 Heaps with dd children heap arithmetic and costs
4 Deleting from the middle of a heap priority-queue operations
5 One Lomuto partition partitioning
6 How often is the maximum compared? indicator variables in quicksort
7 Counting inversions while merging divide and conquer
8 Inserting into a sorted list the decision-tree bound
9 Counting sort by hand counting sort, running sums
10 Radix sort on words radix sort, stability
11 Digit size for 64-bit keys choosing rr in radix sort
12 Bucket sort for a skewed distribution bucket sort
13 Extremes of 1000 values simultaneous min and max
14 A bad input for quickselect worst case of selection
15 Median of medians with groups of seven the selection recurrence

Exercise 1: Where can the third largest be?

A max-heap holds n≥7n \ge 7 distinct keys in positions 00 to n−1n - 1. Which positions can hold the largest, the second largest and the third largest key?

Answer

Largest: position 0. Second largest: position 1 or 2. Third largest: any of positions 1 to 6.

Solution

Every ancestor of a node holds a larger key (the heap property chains along the path to the root). The jj-th largest key has only j−1j - 1 larger keys, so it has at most j−1j - 1 ancestors, that is, its depth is at most j−1j - 1. The largest is at depth 0, the second largest at depth at most 1 (positions 1 and 2), the third largest at depth at most 2 (positions 1 to 6). All these positions are possible: if the second largest is at position 1, the third largest can be at position 2, or at 3 or 4 below the second largest; symmetric arrangements give 5 and 6. See Binary Heaps and the Heap Property.

Exercise 2: Build a heap by hand

Run BUILD-MAX-HEAP on [5, 13, 2, 25, 7, 17, 20, 8, 4]. Give the array after each sift-down call.

Answer

After the calls at positions 3, 2, 1, 0: [5, 13, 2, 25, 7, 17, 20, 8, 4], [5, 13, 20, 25, 7, 17, 2, 8, 4], [5, 25, 20, 13, 7, 17, 2, 8, 4], [25, 13, 20, 8, 7, 17, 2, 5, 4].

Solution

With n=9n = 9 the internal nodes are positions ⌊9/2⌋−1=3\lfloor 9/2 \rfloor - 1 = 3 down to 0. Position 3 holds 25, larger than its children 8 and 4: no change. Position 2 holds 2 with children 17 and 20: it swaps with 20. Position 1 holds 13 with children 25 and 7: it swaps with 25 and is then larger than its new children 8 and 4. Position 0 holds 5: it swaps with 25, then with 13, then with 8.

python · try it yourself
def sift_down(a, i, n):
    while True:
        l, r, big = 2 * i + 1, 2 * i + 2, i
        if l < n and a[l] > a[big]: big = l
        if r < n and a[r] > a[big]: big = r
        if big == i: return
        a[i], a[big] = a[big], a[i]
        i = big

a = [5, 13, 2, 25, 7, 17, 20, 8, 4]
for i in range(len(a) // 2 - 1, -1, -1):
    sift_down(a, i, len(a))
    print(f"after sift-down at {i}: {a}")
after sift-down at 3: [5, 13, 2, 25, 7, 17, 20, 8, 4]
after sift-down at 2: [5, 13, 20, 25, 7, 17, 2, 8, 4]
after sift-down at 1: [5, 25, 20, 13, 7, 17, 2, 8, 4]
after sift-down at 0: [25, 13, 20, 8, 7, 17, 2, 5, 4]

Exercise 3: Heaps with d children

A dd-ary heap stores a tree in which every node has up to dd children, in an array, level by level. Give the index formulas (0-based), the height, and the costs of EXTRACT-MAX and INSERT.

Answer

Children of ii: di+1,…,di+ddi + 1, \ldots, di + d; parent: ⌊(i−1)/d⌋\lfloor (i - 1)/d \rfloor. Height Θ(log⁡dn)\Theta(\log_d n). EXTRACT-MAX costs O(dlog⁡dn)O(d \log_d n), INSERT (and INCREASE-KEY) O(log⁡dn)O(\log_d n).

Solution

Level ℓ\ell holds dℓd^\ell positions, so positions are numbered so that the children of ii follow those of i−1i - 1: node 0 has children 1..d1..d, node 1 has d+1..2dd+1..2d, and in general di+1..di+ddi + 1..di + d. Inverting, the parent of j≥1j \ge 1 is ⌊(j−1)/d⌋\lfloor (j - 1)/d \rfloor. A tree of height hh has at most 1+d+⋯+dh<dh+11 + d + \cdots + d^h < d^{h+1} nodes and at least 1+⋯+dh−1+1>dh−11 + \cdots + d^{h-1} + 1 > d^{h-1}, so h=Θ(log⁡dn)h = \Theta(\log_d n). Sift-down compares a node with all dd children on each level (dd comparisons), so EXTRACT-MAX is O(dlog⁡dn)O(d \log_d n); sift-up makes one comparison per level, so INSERT is O(log⁡dn)O(\log_d n). A larger dd makes inserts and key increases cheaper and extractions dearer, which is why Dijkstra's algorithm on dense graphs can benefit from d>2d > 2.

Exercise 4: Deleting from the middle of a heap

Give an O(lg⁡n)O(\lg n) procedure DELETE(a,i)(a, i) that removes the element at position ii from a max-heap.

Answer

Move the last element into position ii, shrink the heap, then sift the moved element up if it is larger than its new parent, otherwise down.

Solution

Removing the last position keeps the shape. The value yy moved to position ii can violate the heap property in only one direction. The children of ii were at most the deleted value, which was at most its parent. So if yy is larger than the parent of ii, it is also larger than both children, and sift-up repairs everything. Otherwise yy is at most its parent, only a child can be larger, and sift-down repairs it. Each repair walks one path: O(lg⁡n)O(\lg n).

A common bug is to sift only down. In the max-heap [10, 5, 9, 4, 3, 8, 7], deleting position 3 (value 4) moves the last value 7 under the 5 at position 1, and 7 must climb: the result is [10, 7, 9, 5, 3, 8]. See Priority Queues.

Exercise 5: One Lomuto partition

Run LOMUTO-PARTITION on [9, 4, 7, 1, 8, 2, 6, 3, 5] (pivot 5, the last element). What is the result, where does the pivot land, and how many swaps of distinct positions happen, not counting the final pivot swap?

Answer

[4, 1, 2, 3, 5, 7, 6, 9, 8], pivot at index 4, 4 swaps.

Solution

The values smaller than 5 are 4, 1, 2, 3, met in that order, and each is swapped into the small region at positions 0, 1, 2, 3 (each time from a different position, since a[0]=9a[0] = 9 is not small). Then the pivot swaps with a[4]a[4]. The comparisons: always n−1=8n - 1 = 8. See Lomuto Partitioning.

Exercise 6: How often is the maximum compared?

In randomized quicksort on nn distinct keys, what is the expected number of comparisons that involve the largest key znz_n?

Answer

2(Hn−1)≈2ln⁡n2(H_n - 1) \approx 2 \ln n.

Solution

By the analysis in Randomized Quicksort and Its Expected Cost, ziz_i and znz_n are compared with probability 2n−i+1\frac{2}{n - i + 1}. Summing over i=1,…,n−1i = 1, \ldots, n - 1 gives ∑m=2n2m=2(Hn−1)\sum_{m=2}^{n} \frac{2}{m} = 2(H_n - 1). The program checks it exactly for n=7n = 7 by averaging over all permutations (deterministic last-element quicksort on a random permutation has the same distribution).

python · try it yourself
from fractions import Fraction
from itertools import permutations
from math import factorial

def comparisons_with(a, target):
    count, stack = 0, [(0, len(a) - 1)]
    while stack:
        lo, hi = stack.pop()
        if lo >= hi: continue
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            if target in (a[j], pivot): count += 1
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]; i += 1
        a[i], a[hi] = a[hi], a[i]
        stack += [(lo, i - 1), (i + 1, hi)]
    return count

n = 7
avg = Fraction(sum(comparisons_with(list(p), n) for p in permutations(range(1, n + 1))), factorial(n))
H = sum(Fraction(1, k) for k in range(1, n + 1))
print(f"average comparisons involving the maximum: {avg}, 2(H_n - 1) = {2 * (H - 1)}")
average comparisons involving the maximum: 223/70, 2(H_n - 1) = 223/70

Exercise 7: Counting inversions while merging

An inversion is a pair i<ji < j with a[i]>a[j]a[i] > a[j] (Indicator Random Variables computed their expected number). Modify merge sort to count the inversions of an array in O(nlg⁡n)O(n \lg n) time.

Answer

When the merge takes an element from the right half while mm elements of the left half remain, that element forms an inversion with each of those mm: add mm to the count.

Solution

Every inversion has both elements in the left half, both in the right half, or one in each; the recursive calls count the first two kinds, and the merge counts the third. A right-half element yy is merged before exactly the left-half elements larger than it (the merge takes the left element on ties, so equal values are not counted), and those are precisely the remaining ones, since the left half is sorted. The merge's extra work is O(1)O(1) per step, so the recurrence stays T(n)=2T(n/2)+Θ(n)=Θ(nlg⁡n)T(n) = 2T(n/2) + \Theta(n) = \Theta(n \lg n). This is the practice problem Count Inversions.

python · try it yourself
import random

def sort_count(a):
    if len(a) <= 1:
        return a, 0
    mid = len(a) // 2
    left, x = sort_count(a[:mid])
    right, y = sort_count(a[mid:])
    out, i, j, inv = [], 0, 0, x + y
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
            inv += len(left) - i          # right[j] is smaller than every remaining left element
    return out + left[i:] + right[j:], inv

rng = random.Random(9)
for _ in range(200):
    a = [rng.randint(0, 9) for _ in range(rng.randint(0, 30))]
    brute = sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] > a[j])
    assert sort_count(a)[1] == brute
print("matches brute force on 200 random arrays")
print("inversions of [3, 1, 4, 1, 5, 9, 2, 6]:", sort_count([3, 1, 4, 1, 5, 9, 2, 6])[1])
matches brute force on 200 random arrays
inversions of [3, 1, 4, 1, 5, 9, 2, 6]: 8

Exercise 8: Inserting into a sorted list

A sorted array holds nn distinct keys and a new key xx (distinct from them) must be inserted. Show that every comparison-based method needs ⌈lg⁡(n+1)⌉\lceil \lg(n + 1) \rceil comparisons in the worst case to find the position. How many is that for n=1000n = 1000?

Answer

There are n+1n + 1 possible positions, so the decision tree has at least n+1n + 1 leaves and height at least ⌈lg⁡(n+1)⌉\lceil \lg(n+1) \rceil; for n=1000n = 1000 that is 10. Binary search meets the bound.

Solution

Each of the n+1n + 1 gaps (before the first key, between two keys, after the last) is the correct answer for some xx, and different answers need different leaves. A binary tree of height hh has at most 2h2^h leaves, so 2h≥n+12^h \ge n + 1. For n=1000n = 1000: 29=512<1001≤1024=2102^9 = 512 < 1001 \le 1024 = 2^{10}. Binary search halves the number of candidate gaps with each comparison, so it uses exactly ⌈lg⁡(n+1)⌉\lceil \lg(n+1) \rceil in the worst case. Using it inside insertion sort ("binary insertion sort") reduces the comparisons to about lg⁡(n!)\lg(n!), but not the shifts, which stay Θ(n2)\Theta(n^2). See Decision Trees and the Comparison Lower Bound.

Exercise 9: Counting sort by hand

Sort the keys [4, 1, 3, 4, 0, 1, 4, 2] with COUNTING-SORT (k=4k = 4). Give the counts, the running sums, and the output position of each of the three 4s (first, second, third in the input).

Answer

Counts [1, 2, 1, 1, 3], running sums [1, 3, 4, 5, 8]. The 4s go to positions 5, 6 and 7, in input order.

Solution

The block of key 4 is positions c[3]=5c[3] = 5 to c[4]−1=7c[4] - 1 = 7. The backward pass meets the third 4 first (input index 6) and puts it at c[4]−1=7c[4] - 1 = 7, then the second (index 3) at 6, then the first (index 0) at 5. So equal keys come out in input order: the sort is stable. See Counting Sort and Stability.

Exercise 10: Radix sort on words

Sort the three-letter words tan, sea, ant, ten, ask, tea, art, sky with LSD radix sort, one letter per pass. Give the list after each pass.

Answer

By the third letter: sea, tea, ask, tan, ten, ant, art, sky. By the second: tan, sea, tea, ten, sky, ant, art, ask. By the first: ant, art, ask, sea, sky, tan, tea, ten.

Solution

Each pass is a stable sort by one letter, starting with the last. The program prints every pass; check by hand that within each group of equal letters the order of the previous pass is kept.

python · try it yourself
def stable_sort_by(words, pos):
    buckets = {}
    for w in words:                       # appending in input order keeps it stable
        buckets.setdefault(w[pos], []).append(w)
    return [w for letter in sorted(buckets) for w in buckets[letter]]

words = ["tan", "sea", "ant", "ten", "ask", "tea", "art", "sky"]
for pos in [2, 1, 0]:
    words = stable_sort_by(words, pos)
    print(f"by letter {pos}: {', '.join(words)}")
by letter 2: sea, tea, ask, tan, ten, ant, art, sky
by letter 1: tan, sea, tea, ten, sky, ant, art, ask
by letter 0: ant, art, ask, sea, sky, tan, tea, ten

The buckets here are indexed by letters, the counting-sort idea with a dictionary instead of an array of 26 counters. See Radix Sort.

Exercise 11: Digit size for 64-bit keys

You must sort n=220n = 2^{20} keys of b=64b = 64 bits with LSD radix sort, using rr-bit digits, at a cost of ⌈b/r⌉(n+2r)\lceil b/r \rceil (n + 2^r) steps. Which rr is best?

Answer

r=16r = 16: 4 passes, 4(220+216)=4,456,4484(2^{20} + 2^{16}) = 4{,}456{,}448 steps.

Solution

The number of passes ⌈64/r⌉\lceil 64/r \rceil only changes at a few values of rr, so only the smallest rr for each pass count is worth considering: r=13r = 13 (5 passes), 1616 (4), 2222 (3), 3232 (2). Their costs are 5(220+213)≈5.285(2^{20} + 2^{13}) \approx 5.28 million, 4(220+216)≈4.464(2^{20} + 2^{16}) \approx 4.46 million, 3(220+222)≈15.73(2^{20} + 2^{22}) \approx 15.7 million and 2(220+232)≈8.62(2^{20} + 2^{32}) \approx 8.6 billion. Going from 4 to 3 passes would need r=22r = 22, whose 2222^{22} counters cost four times nn per pass.

python · try it yourself
import math
n, b = 2 ** 20, 64
cost = {r: math.ceil(b / r) * (n + 2 ** r) for r in range(1, b + 1)}
best = min(cost, key=cost.get)
print(f"best r = {best}: {math.ceil(b / best)} passes, {cost[best]:,} steps")
for r in [8, 13, 16, 20, 22]:
    print(f"r = {r:>2}: {math.ceil(b / r)} passes, {cost[r]:>11,} steps")
best r = 16: 4 passes, 4,456,448 steps
r =  8: 8 passes,   8,390,656 steps
r = 13: 5 passes,   5,283,840 steps
r = 16: 4 passes,   4,456,448 steps
r = 20: 4 passes,   8,388,608 steps
r = 22: 3 passes,  15,728,640 steps

Exercise 12: Bucket sort for a skewed distribution

The keys are independent, each the maximum of two independent uniform numbers from [0,1)[0, 1), so Pr⁡[X≤x]=x2\Pr[X \le x] = x^2. Equal-width buckets would be crowded near 1. How should a key be assigned to one of nn buckets so that bucket sort runs in expected linear time?

Answer

Use bucket ⌊nx2⌋\lfloor n x^2 \rfloor: the boundaries i/n\sqrt{i/n} give every bucket probability 1n\frac{1}{n}.

Solution

The analysis in Bucket Sort and Its Expected Running Time only used that each key falls into each bucket with probability 1n\frac{1}{n}, independently. Mapping xx to F(x)=x2F(x) = x^2 makes F(X)F(X) uniform on [0,1)[0, 1), so bucket ⌊nF(x)⌋\lfloor n F(x) \rfloor has exactly that property, and E[∑ni2]=2n−1\mathbb{E}[\sum n_i^2] = 2n - 1 again. Because FF is increasing, the buckets are still ordered by key, so concatenating them stays correct.

python · try it yourself
import random

def sum_squares(keys, bucket_of, n):
    sizes = [0] * n
    for x in keys:
        sizes[bucket_of(x)] += 1
    return sum(s * s for s in sizes)

rng = random.Random(4)
n, trials = 2000, 20
equal_width = matched = 0
for _ in range(trials):
    keys = [max(rng.random(), rng.random()) for _ in range(n)]
    equal_width += sum_squares(keys, lambda x: int(n * x), n)
    matched += sum_squares(keys, lambda x: int(n * x * x), n)
print(f"mean sum of squares, equal-width buckets: {equal_width / trials:.0f}")
print(f"mean sum of squares, buckets floor(n x^2): {matched / trials:.0f}   (2n - 1 = {2 * n - 1})")
mean sum of squares, equal-width buckets: 4662
mean sum of squares, buckets floor(n x^2): 3992   (2n - 1 = 3999)

Equal-width buckets would still be linear here (the density is at most 2), but their expected sum of squares is about 7n3\frac{7n}{3} instead of 2n2n, a sixth more work.

Exercise 13: Extremes of 1000 values

How many comparisons does the pairing method use to find both the minimum and the maximum of 1000 values, and how many does running two separate scans use?

Answer

3⋅10002−2=1498\frac{3 \cdot 1000}{2} - 2 = 1498, against 2⋅999=19982 \cdot 999 = 1998.

Solution

For even nn: one comparison for the first pair and three for each of the other 499499 pairs, 1+1497=1498=⌈3n/2⌉−21 + 1497 = 1498 = \lceil 3n/2 \rceil - 2, which is also the lower bound from the adversary argument in Minimum and Maximum Together. Two separate scans need n−1n - 1 each.

Exercise 14: A bad input for quickselect

Deterministic quickselect (last element as pivot, Lomuto partition) is asked for the minimum (k=1k = 1). Which input of size nn makes it slowest, and how many comparisons does it make?

Answer

Increasing input such as 1,2,…,n1, 2, \ldots, n: the pivot is always the maximum, and the total is n(n−1)2\frac{n(n-1)}{2}.

Solution

Each partition of mm elements costs m−1m - 1 comparisons and removes at least the pivot, so the total is at most (n−1)+(n−2)+⋯+1=n(n−1)2(n - 1) + (n - 2) + \cdots + 1 = \frac{n(n-1)}{2}. On increasing input the last element of every remaining subarray is its maximum, so it lands at the right end and only the pivot is removed: the maximum is reached. A random pivot makes the expected cost about 2n2n for the minimum (Randomized Quickselect).

Exercise 15: Median of medians with groups of seven

Redo the analysis of SELECT with groups of 7. How many values are guaranteed on each side of the pivot, and what recurrence results?

Answer

At least 4(⌈12⌈n/7⌉⌉−2)≥2n7−84\left(\left\lceil \frac{1}{2} \lceil n/7 \rceil \right\rceil - 2\right) \ge \frac{2n}{7} - 8 on each side, so T(n)≤T(⌈n/7⌉)+T(5n7+8)+O(n)=O(n)T(n) \le T(\lceil n/7 \rceil) + T(\frac{5n}{7} + 8) + O(n) = O(n).

Solution

Each full group whose median is at least the pivot contributes 4 values at least the pivot (its median and the three below it). At least half of the ⌈n/7⌉\lceil n/7 \rceil groups have such a median; discount the pivot's group and the possibly short last group. This gives 4⋅n14−8=2n7−84 \cdot \frac{n}{14} - 8 = \frac{2n}{7} - 8. The recursive call on one side has at most n−(2n7−8)=5n7+8n - (\frac{2n}{7} - 8) = \frac{5n}{7} + 8 values. Since 17+57=67<1\frac{1}{7} + \frac{5}{7} = \frac{6}{7} < 1, the same substitution as in Median of Medians proves T(n)=O(n)T(n) = O(n); the guess T(n)≤dnT(n) \le dn needs dn7−9d≥cn\frac{dn}{7} - 9d \ge cn, true for d≥14cd \ge 14c and n≥126n \ge 126.

Test yourself

In a max-heap of distinct keys, at which depths can the third largest key be?

  1. only depth 2
  2. depth 1 or 2
  3. any depth
  4. only at a leaf

How many comparisons does any comparison-based method need in the worst case to insert a key into a sorted array of 1000 distinct keys?

  1. 9
  2. 10
  3. 500
  4. 1000

For keys with Pr⁡[X≤x]=x2\Pr[X \le x] = x^2 on [0,1)[0, 1), which bucket index keeps bucket sort's expected time linear with the best constant?

  1. ⌊nx⌋\lfloor nx \rfloor
  2. ⌊nx2⌋\lfloor n x^2 \rfloor
  3. ⌊nx⌋\lfloor n \sqrt{x} \rfloor
  4. ⌊x2⌋\lfloor x^2 \rfloor