Level 5 — MasterySorting & Searching

Sorting & Searching

90 minutes60 marksprintable — key stays hidden on paper

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 T(n)=Ω(nlogn)T(n) = \Omega(n \log n) 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 hh satisfies 2hn!2^h \ge n! 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 Ω(nlogn)\Omega(n\log n). Use the fact that a binary tree with LL leaves has average leaf depth at least log2L\log_2 L. (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 kBTln2k_B T \ln 2 of energy (Landauer's principle). At room temperature T=300KT = 300\,\text{K}, with kB=1.38×1023J/Kk_B = 1.38\times10^{-23}\,\text{J/K}, compute the minimum total energy that any comparison sorter must dissipate to sort n=106n = 10^6 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 nn distinct elements, where the pivot is chosen uniformly at random. Let XX be the total number of element comparisons. Using indicator variables XijX_{ij} (equal to 1 iff the ii-th and jj-th smallest elements, ziz_i and zjz_j, 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 {zi,,zj}\{z_i,\dots,z_j\}. (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 Hn=k=1n1/kH_n = \sum_{k=1}^n 1/k. 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 n=7n=7 (with distinct integers) that still forces Θ(n2)\Theta(n^2) 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 kk-th smallest element. Groups of 5 are used. Prove the key structural lemma that the chosen pivot is greater than at least 3(12n52)3n1063\left(\left\lceil \frac{1}{2}\left\lceil \frac{n}{5}\right\rceil\right\rceil - 2\right) \ge \frac{3n}{10} - 6 elements (and symmetrically less than 3n/106\ge 3n/10 - 6). (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 cc such that T(n)cnT(n) \le cn 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 gg (odd) are used. Show the recurrence becomes T(n)T(n/g)+T(n(g/2/g)(n/2))+O(n)T(n) \le T(n/g) + T(n - (\lceil g/2\rceil/g)(n/2)) + O(n) (to leading order), and derive the condition on gg for linearity: that the two fractional coefficients sum to less than 1. Determine the smallest odd gg that works and confirm g=3g=3 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 aiaja_i \lessgtr a_j. Its execution on all inputs of size nn 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 n!n! distinct orderings of distinct inputs must lead to a distinct leaf (each requires a distinct output permutation). Hence the number of leaves Ln!L \ge n!. 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 hh has at most 2h2^h leaves. Therefore 2hLn!    hlog2(n!).2^h \ge L \ge n! \;\Rightarrow\; h \ge \log_2(n!). The worst-case comparison count equals the longest root-to-leaf path =h=h.

Stirling estimate (4 marks). Using (1), log2(n!)=ln(n!)ln2=nlnnn+O(lnn)ln2=nlog2nnlog2e+O(logn).\log_2(n!) = \frac{\ln(n!)}{\ln 2} = \frac{n\ln n - n + O(\ln n)}{\ln 2} = n\log_2 n - n\log_2 e + O(\log n). The leading term is nlog2nn\log_2 n, so hnlog2n1.4427n+O(logn)=Ω(nlogn)h \ge n\log_2 n - 1.4427\,n + O(\log n) = \Omega(n\log n). ∎

(b) Average-case (5 marks)

The average number of comparisons equals the average leaf depth dˉ\bar d of the tree (2 marks). A binary tree with LL leaves has average leaf depth dˉlog2L\bar d \ge \log_2 L (a "balanced" tree minimizes average depth; formally by Kraft/entropy, dˉlog2L\bar d \ge \log_2 L) (1 mark). With Ln!L \ge n!: \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 Ω(nlogn)\Omega(n\log n). ∎

(c) Landauer energy (6 marks)

Minimum comparisons in worst case log2(n!)\ge \lceil\log_2(n!)\rceil (1 mark). Compute for n=106n=10^6: log2(n!)nlog2nnlog2e.\log_2(n!) \approx n\log_2 n - n\log_2 e. log2(106)=6log210=6(3.32193)=19.9316\log_2(10^6) = 6\log_2 10 = 6(3.32193) = 19.9316. nlog2n=106×19.9316=1.99316×107n\log_2 n = 10^6 \times 19.9316 = 1.99316\times10^7. nlog2e=106×1.44270=1.44270×106n\log_2 e = 10^6 \times 1.44270 = 1.44270\times10^6. So log2(n!)1.99316×1070.144270×107=1.8489×107\log_2(n!) \approx 1.99316\times10^7 - 0.144270\times10^7 = 1.8489\times10^7 comparisons (2 marks).

Energy per erased bit: kBTln2=1.38×1023×300×0.6931=2.870×1021Jk_B T\ln 2 = 1.38\times10^{-23}\times300\times0.6931 = 2.870\times10^{-21}\,\text{J} (1 mark).

Total minimum: E1.8489×107×2.870×1021=5.31×1014J5.3×1014JE \ge 1.8489\times10^7 \times 2.870\times10^{-21} = 5.31\times10^{-14}\,\text{J} \approx \mathbf{5.3\times10^{-14}\,J} (1 mark).

Comment (1 mark): Counting sort does not use element-vs-element comparisons; it uses key values as array indices (bucketing). The Ω(nlogn)\Omega(n\log n) bound applies only to the comparison model, so counting sort's O(n+k)O(n+k) 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 z1<z2<<znz_1 < z_2 < \dots < z_n be sorted order. Consider the set Zij={zi,,zj}Z_{ij}=\{z_i,\dots,z_j\}.

Claim: ziz_i and zjz_j are compared iff the first element of ZijZ_{ij} chosen as a pivot is ziz_i or zjz_j (3 marks).

  • Comparisons only occur against a pivot. While no element of ZijZ_{ij} is chosen as pivot, all of ZijZ_{ij} stays in the same partition (any pivot outside ZijZ_{ij} is either <zi<z_i or >zj>z_j, so does not separate them).
  • Once some zmZijz_m\in Z_{ij} is picked first: if i<m<ji<m<j, then zi,zjz_i,z_j go to opposite partitions and are never compared. If m=im=i or m=jm=j, the pivot is compared with everything in the set, so zi,zjz_i,z_j are compared. Each pair is compared at most once (a pivot is removed after partition).

Probability (4 marks). Among the Zij=ji+1|Z_{ij}| = j-i+1 elements, each is equally likely to be the first chosen as pivot (uniform random pivots). Favourable outcomes: ziz_i or zjz_j first, i.e. 22 of ji+1j-i+1: Pr[Xij=1]=2ji+1.\Pr[X_{ij}=1] = \frac{2}{j-i+1}. \qquad ∎

(b) Expectation (7 marks)

By linearity: E[X]=i<jPr[Xij=1]=i=1n1j=i+1n2ji+1E[X]=\sum_{i<j}\Pr[X_{ij}=1]=\sum_{i=1}^{n-1}\sum_{j=i+1}^{n}\frac{2}{j-i+1} (1 mark).

Substitute k=jik=j-i (kk runs 1ni1\dots n-i): 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 Hn=lnn+γ+O(1/n)H_n = \ln n + \gamma + O(1/n), 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 n=7n=7 instance: A=[1,7,3,2,5,4,6].A = [1,\,7,\,3,\,2,\,5,\,4,\,6]. Here positions lo=0,mid=3,hi=6lo=0,mid=3,hi=6 hold 1,2,61,2,6; median =2=2, 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 {1 element}\{1\text{ element}\} vs {n1}\{n-1\}, giving depth Θ(n)\Theta(n) and total work k=Θ(n2)\sum k = \Theta(n^2). 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 AA into n/5\lceil n/5\rceil groups of ≤5; sort each and take its median (the "medians"). Recursively SELECT the median-of-medians xx of these n/5\lceil n/5\rceil medians. Partition AA around xx; recurse into the side containing rank kk.

Guarantee (5 marks): At least half of the n/5\lceil n/5\rceil groups contribute a median x\le x... consider medians x\ge x: there are 12n/5\ge \lceil \tfrac12\lceil n/5\rceil\rceil such group-medians. In each such group, the median plus the 2 elements above it (3 elements) are x\ge x, except possibly the group containing xx itself and the last (partial) group — subtract 2 groups. Thus the number of elements x\ge x is 3(12n52)3(n102)=3n106.\ge 3\left(\left\lceil\tfrac12\left\lceil\tfrac n5\right\rceil\right\rceil - 2\right) \ge 3\left(\frac{n}{10}-2\right) = \frac{3n}{10}-6. By symmetry 3n/106\ge 3n/10-6 elements are x\le x. Hence each recursive partition discards 3n/106\ge 3n/10-6 elements, so the surviving side has n(3n/106)=7n/10+6\le n-(3n/10-6)=7n/10+6 elements. ∎

(b) Recurrence and substitution (9 marks)

Costs (2 marks): median-finding recursion on n/5\lceil n/5\rceil medians =T(n/5)=T(n/5); recursive select on the ≤7n/10+67n/10+6 side =T(7n/10+6)=T(7n/10+6); grouping, group-medians, partition =O(n)=an=O(n)=an: T(n)T(n/5)+T(7n/10+6)+an.T(n) \le T(n/5) + T(7n/10+6) + an.

Substitution (5 marks): Guess T(n)cnT(n)\le cn for n>n0n> n_0. Then T(n)cn5+c(7n10+6)+an=cn(15+710)+6c+an=910cn+6c+an.T(n) \le c\frac n5 + c\left(\frac{7n}{10}+6\right)+an = cn\left(\frac15+\frac{7}{10}\right)+6c+an = \frac{9}{10}cn + 6c + an. Require 910cn+6c+ancn\frac{9}{10}cn+6c+an \le cn, i.e. an+6c110cnan+6c \le \frac{1}{10}cn, i.e. c10ann60for n120, nn602, take c=20a.c \ge \frac{10an}{n-60}\quad\Longrightarrow\quad \text{for } n\ge 120,\ \frac{n}{n-60}\le 2,\ \text{take } c = 20a. So T(n)=O(n)T(n)=O(n). (Set base case cc large enough for n120n\le120.) (2 marks)

Why groups of 3 fail (2 marks): With groups of 3 the pivot exceeds only 2(12n/32)n/3O(1)\ge 2(\lceil\tfrac12\lceil n/3\rceil\rceil-2)\approx n/3-O(1) elements, so the recursion is T(n)T(n/3)+T(2n/3)+O(n)T(n)\le T(n/3)+T(2n/3)+O(n). Coefficients 13+23=1\tfrac13+\tfrac23=1, so the guessed substitution gives T(n)cn+O(n)T(n)\le cn+O(n) — the linear guess fails; solving exactly yields T(n)=Θ(nlogn)T(n)=\Theta(n\log n), not linear.

(c) General group size (4 marks)

With odd group size gg: median-finding costs T(n/g)T(n/g). The pivot exceeds g/2gn2\ge \frac{\lceil g/2\rceil}{g}\cdot\frac n2 elements (half the groups, g/2\lceil g/2\rceil each, over n/gn/g groups → to leading order g/2gn2\tfrac{\lceil g/2\rceil}{g}\cdot\tfrac n2). Surviving side $\le n - \tfr