Sorting & Searching
Time limit: 90 minutes Total marks: 60 Instructions: Answer all three questions. Full derivations and proofs are required. Pseudocode must be precise; asymptotic claims must be justified. Partial credit is awarded for rigorous intermediate steps.
Question 1 — Decision-Tree Lower Bound & a Physical Analogy (20 marks)
(a) State the comparison-sort model precisely, and prove the lower bound for the worst-case number of comparisons of any comparison-based sorting algorithm, using the decision-tree argument. Include the derivation showing why the tree height satisfies and complete the estimate using Stirling's approximation \ln(n!) = n\ln n - n + O(\ln n). \tag{1} (9 marks)
(b) Extend the argument to derive a lower bound on the average-case number of comparisons, i.e. the average leaf depth of the decision tree, and show it is also . Use the fact that a binary tree with leaves has average leaf depth at least . (5 marks)
(c) Cross-domain. An idealized "sorting engine" performs one comparison per Landauer-erasure step, each irreversibly erasing one bit and dissipating at least of energy (Landauer's principle). At room temperature , with , compute the minimum total energy that any comparison sorter must dissipate to sort distinct items in the worst case, using your bound from (a). Express the answer to two significant figures and comment on why counting sort could evade this bound. (6 marks)
Question 2 — Randomized Quicksort Expectation (20 marks)
(a) Consider randomized quicksort on distinct elements, where the pivot is chosen uniformly at random. Let be the total number of element comparisons. Using indicator variables (equal to 1 iff the -th and -th smallest elements, and , are ever compared), prove that \Pr[X_{ij}=1] = \frac{2}{j-i+1}. \tag{2} Justify carefully why two elements are compared iff one of them is the first pivot chosen from the set . (7 marks)
(b) Hence prove E[X] = \sum_{i=1}^{n-1}\sum_{j=i+1}^{n} \frac{2}{j-i+1} \le 2n H_n = 2n\left(\ln n + O(1)\right) = O(n\log n), \tag{3} where . Show the algebraic reduction of the double sum to the harmonic form explicitly. (7 marks)
(c) Build. Give pseudocode for a Hoare-partition quicksort with a median-of-three pivot, and construct an explicit input of length (with distinct integers) that still forces behaviour on your scheme despite median-of-three. Explain precisely why your adversarial input defeats the heuristic. (6 marks)
Question 3 — Median-of-Medians Selection: Recurrence & Proof (20 marks)
(a) Describe the median-of-medians SELECT(A, k) algorithm that finds the -th smallest element. Groups of 5 are used. Prove the key structural lemma that the chosen pivot is greater than at least
elements (and symmetrically less than ). (7 marks)
(b) Write the recurrence for the worst-case running time using this guarantee, and prove by the substitution method that T(n) \le \frac{T(n/5) + T(7n/10 + 6) + O(n)}{} \implies T(n) = O(n). \tag{4} Explicitly find the constant such that works, and show where the argument breaks if groups of 3 are used instead of 5. (9 marks)
(c) Cross-domain (math). Suppose instead groups of size (odd) are used. Show the recurrence becomes (to leading order), and derive the condition on for linearity: that the two fractional coefficients sum to less than 1. Determine the smallest odd that works and confirm fails. (4 marks)
Answer keyMark scheme & solutions
Question 1
(a) Decision-tree lower bound (9 marks)
Model (1 mark). A comparison sort accesses input only via comparisons . Its execution on all inputs of size forms a binary decision tree: each internal node is a comparison with two outcomes (branches), each leaf a permutation output.
Leaves ≥ n! (2 marks). For the algorithm to be correct, every one of the distinct orderings of distinct inputs must lead to a distinct leaf (each requires a distinct output permutation). Hence the number of leaves . Why: two inputs requiring different sorted rearrangements cannot follow identical comparison outcomes yet produce the correct answer.
Height bound (2 marks). A binary tree of height has at most leaves. Therefore The worst-case comparison count equals the longest root-to-leaf path .
Stirling estimate (4 marks). Using (1), The leading term is , so . ∎
(b) Average-case (5 marks)
The average number of comparisons equals the average leaf depth of the tree (2 marks). A binary tree with leaves has average leaf depth (a "balanced" tree minimizes average depth; formally by Kraft/entropy, ) (1 mark). With : \bar d \ge \log_2(n!) = n\log_2 n - \Theta(n) = \Omega(n\log n). \tag{2 marks} So even the average case is . ∎
(c) Landauer energy (6 marks)
Minimum comparisons in worst case (1 mark). Compute for : . . . So comparisons (2 marks).
Energy per erased bit: (1 mark).
Total minimum: (1 mark).
Comment (1 mark): Counting sort does not use element-vs-element comparisons; it uses key values as array indices (bucketing). The bound applies only to the comparison model, so counting sort's sidesteps both the decision-tree bound and this Landauer floor (though it dissipates energy per array write instead).
Question 2
(a) Comparison probability (7 marks)
Let be sorted order. Consider the set .
Claim: and are compared iff the first element of chosen as a pivot is or (3 marks).
- Comparisons only occur against a pivot. While no element of is chosen as pivot, all of stays in the same partition (any pivot outside is either or , so does not separate them).
- Once some is picked first: if , then go to opposite partitions and are never compared. If or , the pivot is compared with everything in the set, so are compared. Each pair is compared at most once (a pivot is removed after partition).
Probability (4 marks). Among the elements, each is equally likely to be the first chosen as pivot (uniform random pivots). Favourable outcomes: or first, i.e. of :
(b) Expectation (7 marks)
By linearity: (1 mark).
Substitute ( runs ): E[X] = \sum_{i=1}^{n-1}\sum_{k=1}^{n-i}\frac{2}{k+1} < \sum_{i=1}^{n-1}\sum_{k=1}^{n}\frac{2}{k+1} < \sum_{i=1}^{n-1} 2\sum_{k=1}^{n}\frac1k = 2(n-1)H_n. \tag{4 marks} Since , E[X] < 2nH_n = 2n\ln n + O(n) = O(n\log n). \qquad ∎ \tag{2 marks}
(c) Adversarial median-of-three (6 marks)
Pseudocode (3 marks):
QUICKSORT(A, lo, hi):
if lo < hi:
p = HOARE_PARTITION(A, lo, hi)
QUICKSORT(A, lo, p)
QUICKSORT(A, p+1, hi)
HOARE_PARTITION(A, lo, hi):
mid = (lo+hi)//2
# median-of-three: median of A[lo], A[mid], A[hi]
pivot = median(A[lo], A[mid], A[hi])
i = lo-1; j = hi+1
while true:
do i=i+1 while A[i] < pivot
do j=j-1 while A[j] > pivot
if i >= j: return j
swap A[i], A[j]
Adversarial input (3 marks). Median-of-three only guarantees the pivot is not the extreme of the three sampled positions; it can still be near-extreme of the whole array. A "median-of-three killer" arranges that each recursive call's sampled median is the second-smallest remaining element. One concrete instance: Here positions hold ; median , the 2nd smallest. Partition splits off just one element, leaving a size-6 subproblem whose sampled median is again near-minimal. Recursively the split is vs , giving depth and total work . Why it defeats the heuristic: median-of-three protects only against the fully sorted/reverse-sorted patterns; an adversary who knows the fixed sampling positions can plant a permutation making the sampled median an extreme rank of the actual data.
Question 3
(a) Structural lemma (7 marks)
Algorithm (2 marks): Partition into groups of ≤5; sort each and take its median (the "medians"). Recursively SELECT the median-of-medians of these medians. Partition around ; recurse into the side containing rank .
Guarantee (5 marks): At least half of the groups contribute a median ... consider medians : there are such group-medians. In each such group, the median plus the 2 elements above it (3 elements) are , except possibly the group containing itself and the last (partial) group — subtract 2 groups. Thus the number of elements is By symmetry elements are . Hence each recursive partition discards elements, so the surviving side has elements. ∎
(b) Recurrence and substitution (9 marks)
Costs (2 marks): median-finding recursion on medians ; recursive select on the ≤ side ; grouping, group-medians, partition :
Substitution (5 marks): Guess for . Then Require , i.e. , i.e. So . (Set base case large enough for .) (2 marks)
Why groups of 3 fail (2 marks): With groups of 3 the pivot exceeds only elements, so the recursion is . Coefficients , so the guessed substitution gives — the linear guess fails; solving exactly yields , not linear.
(c) General group size (4 marks)
With odd group size : median-finding costs . The pivot exceeds elements (half the groups, each, over groups → to leading order ). Surviving side $\le n - \tfr