Exercises — Quick sort randomization — expected O(n log n)
This page is a self-testing ladder. Every problem below builds on the parent note Quick sort randomization. Attempt each one on paper before opening its solution. The levels climb from "can you recall the formula" (L1) to "can you invent a proof from scratch" (L5).
Everything rests on three facts from the parent note, restated in plain words so you never have to flip back:
Recall The three facts every problem here uses
- Two elements are compared only when one is the pivot. After a pivot splits the array, elements on opposite sides never meet again. So each pair is compared at most once.
- The compare probability. If are the elements in sorted order (so is the -th smallest), then and are compared with probability . Here is just the gap — how far apart they sit in sorted order.
- The total. Expected comparisons , and this is , where is the harmonic number.
Symbols we will keep reusing (each earned once, here):
- — the number of elements to sort.
- — the -th smallest element (its rank is ). This is not the array position; it is where the element would sit once sorted.
- — the gap between two ranks. Adjacent elements have .
- — the indicator: it equals if and ever get compared, else . See Indicator Random Variables.
- — the total comparison count, ; its average is what every exercise computes.
- — the harmonic number above.
Level 1 — Recognition
L1.1
State, in one line each: (a) the worst-case time of randomized quicksort, and (b) its expected time on any input.
Recall Solution
(a) Worst case is still — you could flip unlucky coins that always pick an extreme pivot. (b) Expected time is for every input. Randomization removes bad inputs, not bad luck.
L1.2
Write down (the probability they are compared) as a formula in and , and separately as a formula in the gap .
Recall Solution
. The set has members; exactly of them ( and ) are "good" first-pivots.
L1.3
For , list the gaps that occur and how many pairs have each gap.
Recall Solution
With ranks , a pair with gap needs and both in range, so runs , giving pairs.
| gap | pairs | count |
|---|---|---|
| 1 | (1,2)(2,3)(3,4)(4,5)(5,6) | 5 |
| 2 | (1,3)(2,4)(3,5)(4,6) | 4 |
| 3 | (1,4)(2,5)(3,6) | 3 |
| 4 | (1,5)(2,6) | 2 |
| 5 | (1,6) | 1 |
Total pairs . ✅
Level 2 — Application
L2.1
Compute the exact expected number of comparisons for . (This appears in the parent note — reproduce it yourself.)
Recall Solution
Group by gap , using count and probability :
- : pairs
- : pairs
- : pair
L2.2
Compute exactly for .
Recall Solution
Count , probability :
- :
- :
- :
- :
L2.3
Two elements are adjacent in sorted order (gap ). What is the probability they are compared, and why is it exactly that value?
Recall Solution
— they are always compared. Reason: the set between them is just , only two elements. Whichever of the two is picked as a pivot first, the other is still in its subarray, so a comparison happens. There is no "middle" element that could separate them. Adjacent elements can never be split apart before one becomes a pivot.
Level 3 — Analysis
L3.1
Show that the double sum collapses to a single-variable sum in the gap : Explain why the coefficient is .
Recall Solution
Start from . Set . For a fixed gap , the pair is valid whenever and , i.e. runs from to . That is exactly pairs, each contributing the same probability because the probability depends only on . Grouping them: Why regroup? The original sum has two indices but only one quantity that matters — the gap. Collapsing to turns a messy double sum into a single sum we can bound.
L3.2
Using the collapsed form, prove the clean upper bound where .
Recall Solution
From L3.1, (dropping the only makes each term larger). Let , so as runs , runs : Since , this is .
Reading the figure below. The bars visualise why grows only like . The horizontal axis is (the index of each harmonic term); the vertical axis is the value . Each lavender bar sits over the interval with height , so its area equals the harmonic term — and the total bar area is exactly . The coral curve is , whose area from to is . Because every bar's top-left corner touches the curve while the bar overhangs to the right, the bars trap between and . That is the picture behind "", which turns into .

L3.3
Give a numeric lower bound on for large by keeping the term, to show (not just ).
Recall Solution
The first piece is . The second piece: each , so the whole second sum is , i.e. only . Therefore The factor is genuinely there — quicksort is not secretly linear.
Level 4 — Synthesis
L4.1
Consider randomized quickselect (find the -th smallest using random pivots, recursing into only one side). Argue why its expected comparison count is — linear, not — by adapting the compare-probability idea.
Recall Solution
Setup. At each step quickselect partitions the current live subarray around a random pivot, then keeps recursing only into the one side that still contains the target rank . The work done at a step is one partition pass, which costs a comparison for each element of the live subarray — so the total comparison count is just the sum of the sizes of the live subarrays over all steps. Call the size at step the value ; the total is , and each partition costs at most comparisons. The constant we call below is simply the per-element bookkeeping cost of one comparison (a fixed number like ); it is a constant only so the final answer reads as rather than a specific count — you may set and read the argument as counting comparisons directly.
Why the subarray shrinks by a constant factor in expectation. A uniformly random pivot has a rank that is uniform in . Split into quarters. With probability the pivot's rank lands in the middle half (between the and marks). Whenever it does, both resulting sides have size at most , so the side we keep is at most no matter which side holds the target. Therefore, with probability at least the next live size is , and with the other it is at most . The expected next size is thus at most A "good split" (factor ) happens on at least half of steps, so the sizes shrink geometrically; using the looser per-step contraction already suffices, but the classic textbook bound uses the figure to say a good split arrives every steps in expectation.
The geometric sum. Because the expected live size after each good split is at most of the previous, the expected total work is bounded by a geometric series with ratio : Key contrast with sort: sorting must recurse into both sides (work at every level levels), while selection follows one side (work forms a shrinking geometric sum, total ). The deterministic guaranteed-linear cousin is Median of Medians.
L4.2
A colleague proposes: shuffle the array once uniformly at random, then run plain last-element-pivot quicksort. Prove this has the same expected cost and explain the single practical downside.
Recall Solution
After a uniform shuffle, at every recursive call the elements inside a subarray are in uniformly random order, so the last element is a uniformly random pivot of that subarray — exactly the distribution random-pivot quicksort produces. Same pivot-rank distribution same compare probabilities same . Downside: the shuffle is an extra pass and random numbers up front, whereas random pivots draw randomness lazily, only as needed. Both are Las Vegas algorithms: always correct, runtime random.
L4.3
Compare randomized quicksort with Merge Sort in one paragraph, addressing: (i) worst case, (ii) expected case, (iii) extra memory, (iv) which one an adversary can hurt.
Recall Solution
(i) Worst case: merge sort is a guaranteed ; randomized quicksort's worst case is but only with vanishing probability. (ii) Expected case: both ; quicksort's constant factor is usually smaller (in-cache partitioning, no merge buffer). (iii) Memory: merge sort needs extra space for merging; quicksort sorts in place with stack. (iv) An adversary cannot force merge sort's worst case (it has none) and cannot force randomized quicksort's worst case either (cost depends on hidden coin flips, not on the input) — but can force deterministic quicksort's with sorted input.
Level 5 — Mastery
L5.1
Prove the exact closed form for randomized quicksort, starting from .
Recall Solution
Substitute (so , and runs ): Now and : Combine the last two: . Hence Check against L2.2 (): . Then . ✅ Matches.
L5.2
Use L5.1 to verify the answer and to compute for exactly.
Recall Solution
: . Then . ✅ Matches L2.1. : . Then
L5.3
Forecast-then-verify. For , first estimate using , then compare to the exact formula. What is the relative error of the estimate?
Recall Solution
Forecast: . Estimate: Verify: the exact , giving . Relative error of the approximation: about — the approximation is essentially exact at this scale. This confirms for large .
Recall One-line recap of the whole ladder
Compare-probability (L1) → plug into small (L2) → collapse the double sum and bound it with (L3) → transfer the idea to selection, shuffling, and merge sort (L4) → nail the exact closed form (L5).