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 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 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 distinct keys in positions to . 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 -th largest key has only larger keys, so it has at most ancestors, that is, its depth is at most . 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 the internal nodes are positions 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.
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 -ary heap stores a tree in which every node has up to 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 : ; parent: . Height . EXTRACT-MAX costs , INSERT (and INCREASE-KEY) .
Solution
Level holds positions, so positions are numbered so that the children of follow those of : node 0 has children , node 1 has , and in general . Inverting, the parent of is . A tree of height has at most nodes and at least , so . Sift-down compares a node with all children on each level ( comparisons), so EXTRACT-MAX is ; sift-up makes one comparison per level, so INSERT is . A larger makes inserts and key increases cheaper and extractions dearer, which is why Dijkstra's algorithm on dense graphs can benefit from .
Exercise 4: Deleting from the middle of a heap
Give an procedure DELETE that removes the element at position from a max-heap.
Answer
Move the last element into position , 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 moved to position can violate the heap property in only one direction. The children of were at most the deleted value, which was at most its parent. So if is larger than the parent of , it is also larger than both children, and sift-up repairs everything. Otherwise is at most its parent, only a child can be larger, and sift-down repairs it. Each repair walks one path: .
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 is not small). Then the pivot swaps with . The comparisons: always . See Lomuto Partitioning.
Exercise 6: How often is the maximum compared?
In randomized quicksort on distinct keys, what is the expected number of comparisons that involve the largest key ?
Answer
.
Solution
By the analysis in Randomized Quicksort and Its Expected Cost, and are compared with probability . Summing over gives . The program checks it exactly for by averaging over all permutations (deterministic last-element quicksort on a random permutation has the same distribution).
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 with (Indicator Random Variables computed their expected number). Modify merge sort to count the inversions of an array in time.
Answer
When the merge takes an element from the right half while elements of the left half remain, that element forms an inversion with each of those : add 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 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 per step, so the recurrence stays . This is the practice problem Count Inversions.
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 distinct keys and a new key (distinct from them) must be inserted. Show that every comparison-based method needs comparisons in the worst case to find the position. How many is that for ?
Answer
There are possible positions, so the decision tree has at least leaves and height at least ; for that is 10. Binary search meets the bound.
Solution
Each of the gaps (before the first key, between two keys, after the last) is the correct answer for some , and different answers need different leaves. A binary tree of height has at most leaves, so . For : . Binary search halves the number of candidate gaps with each comparison, so it uses exactly in the worst case. Using it inside insertion sort ("binary insertion sort") reduces the comparisons to about , but not the shifts, which stay . 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 (). 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 to . The backward pass meets the third 4 first (input index 6) and puts it at , 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.
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 keys of bits with LSD radix sort, using -bit digits, at a cost of steps. Which is best?
Answer
: 4 passes, steps.
Solution
The number of passes only changes at a few values of , so only the smallest for each pass count is worth considering: (5 passes), (4), (3), (2). Their costs are million, million, million and billion. Going from 4 to 3 passes would need , whose counters cost four times per pass.
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 , so . Equal-width buckets would be crowded near 1. How should a key be assigned to one of buckets so that bucket sort runs in expected linear time?
Answer
Use bucket : the boundaries give every bucket probability .
Solution
The analysis in Bucket Sort and Its Expected Running Time only used that each key falls into each bucket with probability , independently. Mapping to makes uniform on , so bucket has exactly that property, and again. Because is increasing, the buckets are still ordered by key, so concatenating them stays correct.
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 instead of , 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
, against .
Solution
For even : one comparison for the first pair and three for each of the other pairs, , which is also the lower bound from the adversary argument in Minimum and Maximum Together. Two separate scans need each.
Exercise 14: A bad input for quickselect
Deterministic quickselect (last element as pivot, Lomuto partition) is asked for the minimum (). Which input of size makes it slowest, and how many comparisons does it make?
Answer
Increasing input such as : the pivot is always the maximum, and the total is .
Solution
Each partition of elements costs comparisons and removes at least the pivot, so the total is at most . 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 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 on each side, so .
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 groups have such a median; discount the pivot's group and the possibly short last group. This gives . The recursive call on one side has at most values. Since , the same substitution as in Median of Medians proves ; the guess needs , true for and .
Test yourself
In a max-heap of distinct keys, at which depths can the third largest key be?
- only depth 2
- depth 1 or 2
- any depth
- 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?
- 9
- 10
- 500
- 1000
For keys with on , which bucket index keeps bucket sort's expected time linear with the best constant?