Memra

Randomized quicksort & expected analysis

◈ 4 cards

RANDOMIZED-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:

  1. 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.
  2. 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.

sortedz₁z₂z₃z₄z₅z₆Z₂,₅ — 4 candidatespivot z₃z₁z₂z₃z₄z₅z₆low sidehigh sidePr[compare] = 2/(j−i+1) = 2/4.
The comparison lemma. Only z₂ or z₅ being the first pivot out of Z₂,₅ makes the pair meet; any interior pivot separates them for good — 2 of 4 candidates, hence 2/(j−i+1).
NORMAL ~/memra/learn/comp-372/randomized-quicksort utf-8 LF