Randomized quicksort & expected analysis
◈ 4 cardsRANDOMIZED-PARTITION defeats the adversary; expected Θ(n lg n) on ANY input via the indicator-variable / harmonic-sum argument.
Move the worst case off the input
Plain quicksort fails on sorted input because the input controls the pivot. RANDOMIZED-PARTITION breaks that link: before partitioning, pick a uniform random index , swap , then run ordinary PARTITION. Now the pivot is a random element, so no fixed input can force bad behaviour — an adversary would have to predict the coin flips. The worst case is still in principle, but it now depends on the randomness, not the data, and occurs with negligible probability. We therefore analyze expected running time, which is for every input.
The indicator-variable proof (the examined argument)
Let the sorted order be and define . Two facts:
- Lemma (when compared). and are compared iff the first pivot chosen from is or ; any interior element chosen first splits them apart forever. And no pair is compared twice.
- Probability. All elements of are equally likely to be the first pivot, and exactly two of them () cause a comparison, so .
Let . By linearity of expectation,
where is the harmonic series. Since quicksort's time is , the expected running time is — unconditionally, on any input.
Worked example
With a fixed seed, randomized quicksort sorts (note the duplicate s) to . Because the output of a correct sort is deterministic even though the pivot choices are random, the exercise checks the sorted result against Python's sorted() — never the internal coin flips.