Exercises — Module 20 (Optimum Sorting and Sorting Networks)
Self-contained problems on this module's material — the information-theoretic lower bound , Ford–Johnson merge insertion and its count , sorting networks, and the zero-one principle. You can work every one without the books: each states the problem in full, gives a hint to peek at when stuck, and a worked answer sketch to check against after you try. Numeric answers here are reproduced by the code you write in the lab (or a few lines at a REPL).
Ratings follow Knuth's scale (00–50; M = needs mathematics, ▶ = especially
instructive). Where a problem mirrors a TAOCP exercise, its number in §5.3 is
noted for readers who own Volume 3.
Tracking
| # | Topic | Rating | Status |
|---|---|---|---|
| 1 | vs. the binary-insertion count | 10 | ⬜ |
| 2 | ▶ Prove merge insertion costs | 22 | ⬜ |
| 3 | Hand-trace merge insertion at (26 comparisons) | 20 | ⬜ |
| 4 | Where does fail, for ? | 24 | ⬜ |
| 5 | ▶ Prove the zero-one principle (Theorem Z) | 20 | ⬜ |
| 6 | Batcher's odd–even merge correctness via the 0-1 principle | 22 | ⬜ |
| 7 | ▶ Depth and comparators | 28 | ⬜ |
| 8 | Minimum-comparator networks for | 30 | ⬜ |
Problems
1. vs. the binary-insertion count (rating 10 · cf. 5.3.1–2)
Problem. Binary insertion sort inserts the -th element into a sorted run of elements using a binary search, which costs comparisons. So its worst case is . One might guess this equals the information-theoretic lower bound . Compute both for , decide whether the identity holds, and reconcile the two quantities.
Hint. Compare the two tables term by term. For the inequality direction, use , then take .
Answer sketch. The values are
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 3 | 5 | 7 | 10 | 13 | 16 | |
| 0 | 1 | 3 | 5 | 8 | 11 | 14 | 17 |
They agree for but diverge from on (), so the identity is false. What is always true is : since ,
So binary insertion is never below the lower bound and matches it only when no comparison is "wasted." A comparison is wasted exactly when it searches a range whose size is not one less than a power of two — this is the very inefficiency merge insertion (Problems 2–3) is engineered to avoid. (A closed form falls out of the sum: , which you can check against the table.)
2. ▶ Prove merge insertion costs (rating M22 · cf. 5.3.1–3)
Problem. Algorithm M (Ford–Johnson merge insertion) sorts elements. Show that its worst-case comparison count is
equivalently with .
Hint. Track one increment. When the algorithm has already placed the first elements of the main chain and inserts the next partner , how large is the range it binary-searches, and why is that range's size always for the current Jacobsthal group ? Sum the per-insertion costs over the grouping.
Answer sketch. The recurrence follows from the module's "budget" accounting. The Jacobsthal grouping (group boundaries , inserting each group from its top index down) is chosen so that every insertion in group binary-searches a range of size , which costs exactly comparisons — none wasted. Charging the -th element folded into the chain the cost of the group it lands in gives the increment ; the inside the ceiling is exactly the fraction that turns the Jacobsthal group index into a per- formula. Summing telescopes to . A quick numeric check of the increments confirms the shape: the added cost for is , giving running totals — precisely the table in the lesson. (The full proof that the grouping achieves these range sizes for every is Algorithm M's invariant; the instructive step is seeing why is the "perfect fit" that makes tight.)
3. Hand-trace merge insertion at (rating 20 · cf. 5.3.1–4)
Problem. Carry out Algorithm M by hand on 11 elements and confirm it uses exactly comparisons in the worst case, matching .
Hint. Break the 26 into its phases: pairing comparisons, the recursive sort of the larger halves, and the group-by-group binary insertions. Use the per-element increments from Problem 2.
Answer sketch. Pair the 11 elements into pairs with one left over; comparing each pair costs 5 comparisons and yields larger elements and their smaller partners (plus the leftover). Recursively merge-insertion-sort the 5 larger elements: that costs . The main chain is — sits in front for free. Now binary-insert the remaining smaller elements and the leftover in Jacobsthal order (groups , then , with the leftover folded in at its group), each insertion hitting a range of size . Adding the insertion costs to reaches 26 total. Since as well, merge insertion is comparison-optimal at : . (Contrast , where but — the first size where the counting bound is provably loose.)
4. Where does fail, for ? (rating 24 · cf. 5.3.1–8)
Problem. Merge insertion meets the lower bound for small . Tabulate and for , identify the first where they differ, and explain why a loose lower bound at that does not contradict the lower-bound theorem.
Hint. Compute both columns. Watch for the first strict inequality; then recall what the theorem of §1 actually asserts (a floor on every algorithm, not the exact truth).
Answer sketch. The two columns agree for , first differ at ( vs. ), stay apart through , and coincide again at and :
| 11 | 12 | 13 | 14 | … | 19 | 20 | 21 | |
|---|---|---|---|---|---|---|---|---|
| 26 | 29 | 33 | 37 | … | 57 | 62 | 66 | |
| 26 | 30 | 34 | 38 | … | 58 | 62 | 66 |
No contradiction: the theorem says every comparison sort needs at least comparisons — a lower bound. The true minimum can exceed it, and at it does (, achieved by merge insertion). A binary tree of height 29 has leaf-slots, comfortably more than , yet those leaves cannot be packed into a consistent comparison tree — the looseness is a real feature of the problem's geometry, not an arithmetic slack. (The re-coincidence at shows the gap is not monotone; is known only for small and is an open problem in general.)
5. ▶ Prove the zero-one principle (Theorem Z) (rating M20 · cf. 5.3.4–1)
Problem. Prove Theorem Z: a comparator network sorts all inputs (from any ordered set) if and only if it sorts all inputs consisting only of 0s and 1s.
Hint. "Only if" is immediate. For "if," suppose the network fails on some input with unsorted output ; build a monotone threshold map that turns 's inversion into a 0-1 counterexample. You need the fact that a single comparator commutes with any nondecreasing .
Answer sketch. () Trivial: 0-1 inputs are among all inputs. () The crux is that comparators commute with monotone maps: a comparator outputs and , and any nondecreasing satisfies and ; applying this comparator by comparator, running the network on yields , where is the network's output on . Now suppose the network fails on some , so its output has an inversion . Take the threshold function
which is nondecreasing. Then the network on the 0-1 input outputs , which has immediately before — unsorted. So is a 0-1 input the network fails to sort, contradicting the hypothesis. Hence the network sorts every input. (This is a reduction by a well-chosen map: a bad general input is compressed to a bad 0-1 input.)
6. Batcher's odd–even merge correctness via the 0-1 principle (rating 22 · cf. 5.3.4–6)
Problem. Use the zero-one principle to prove Batcher's odd–even merge sorts. It suffices to show the merge combines two already-sorted 0-1 halves into one sorted 0-1 sequence. Then conclude the full network (recursive sort-halves-then-merge) sorts.
Hint. A sorted 0-1 sequence is a block of 0s then a block of 1s, described by one number: its count of 1s. Track how the counts of 1s in the even-indexed and odd-indexed subsequences of a sorted half relate, and what the final "cleanup" comparator sweep fixes.
Answer sketch. By Theorem Z (Problem 5) we need only handle 0-1 inputs. A
sorted 0-1 half of length is fully described by its number of 1s. Split each
half into even- and odd-indexed subsequences; the number of 1s in the even
subsequence and in the odd subsequence of a sorted 0-1 half differ by at most 1,
so after recursively merging the evens together and the odds together, the two
merged streams are each sorted (0s then 1s) and their 1-counts differ by at most
a small bounded amount. The interleaved result is therefore sorted except
possibly for a single adjacent out-of-order pair, which is exactly what the final
sweep of neighbour comparators corrects — leaving one sorted 0-1 sequence. Since
the merge sorts all 0-1 inputs, by Theorem Z it merges all inputs. The full
network sorts each half (by induction) and then merges, so it sorts every 0-1
input and hence — again by Theorem Z — every input. This is why the module proves
correctness over 0-1 sequences rather than unwinding the -way recursion: the
counting argument on 1-counts is the whole content. (You verify it concretely in
Stage 4 by enumerating all binary strings with sorts_all_zero_one.)
7. ▶ Depth and comparators (rating M28 · cf. 5.3.4–10)
Problem. Prove two lower bounds for any sorting network on wires: (a) its depth is at least ; (b) its number of comparators is at least .
Hint. For (a), bound how many input wires can influence a given output wire after parallel steps. For (b), view the whole network as a comparison sort and count the outcomes it can distinguish — each comparator is one yes/no branch.
Answer sketch. (a) Depth. Say a comparator step "grows" the set of input wires an output can depend on. Before any step, each output wire depends on the 1 input on that wire. A parallel step joins the dependency sets of the two wires of each comparator, so it can at most double the size of any wire's dependency set. After steps a wire depends on at most inputs. To sort, the wire holding the minimum must be able to depend on all inputs (any of them could be the smallest), so , giving . (b) Comparators. A network with comparators is a comparison sort: at each comparator the two values either swap or not — a binary outcome. Tracing a single input through the network selects one of at most swap/no-swap patterns, and inputs that are ordered differently must follow distinguishable patterns to be sorted correctly. So the network distinguishes at most outcomes but must handle orderings: , hence . This is the same counting argument as the comparison-sort lower bound of §1, applied to comparators. Both bounds are often loose (see Problem 8): Batcher's network on uses 19 comparators against a bound of , and depth 6 against .
8. Minimum-comparator networks for (rating 30 · cf. 5.3.4–38)
Problem. Let be the fewest comparators in any sorting network on wires. Using the counting lower bound (Problem 7b) and Batcher's construction as an upper bound, investigate for : how tight is the lower bound, and what are the established optimal values?
Hint. Tabulate the counting bound and Batcher's counts where they apply, then compare to the known optima. Ask the same question the lesson asks about : is the cheap bound the truth?
Answer sketch. The counting bound gives for , but the true minima — established by decades of construction and, for , exhaustive computer search — are
So the bound is tight only for and grows loose afterward (gaps ) — the very same "cheap bound vs. hard truth" phenomenon the lesson highlights for at . Batcher's odd–even network hits the optimum at the powers of two in range (: 1; : 5; : 19), so it is not just asymptotically good but exactly optimal for those small ; non-power-of-two optima like and require hand-crafted constructions. The exact values of are known only for small and remain a research frontier for larger — a comparator-count analogue of the open problem of computing . (These optima are verifiable published results; the module derives the lower bound and one upper bound here, and the gap between them is the point of the exercise.)
Your solutions
Use this space to log your own work — a restated problem, your approach, and how it compared with the sketch above.
Exercise N (rating RR)
Approach. Answer / proof. Compared with the sketch: what you did differently, what you missed.