Randomized Quicksort and Its Expected Cost
Deterministic quicksort has a fatal weakness: some inputs, and very ordinary ones like sorted arrays, make it quadratic. The fix is to stop letting the input choose the pivot. Randomized quicksort picks the pivot uniformly at random from the current subarray. Then no input is bad; every input has the same expected cost, and that cost is about comparisons. This lesson derives that number exactly with indicator random variables, in the style of Indicator Random Variables, and checks it by enumeration and simulation.
The algorithm
Only the partition step changes: swap a random element into the pivot position, then partition as before.
RANDOMIZED-PARTITION(a, lo, hi)
1 r = a uniformly random integer in lo..hi
2 swap a[r] and a[hi]
3 return LOMUTO-PARTITION(a, lo, hi)
RANDOMIZED-QUICKSORT(a, lo, hi)
1 if lo < hi
2 p = RANDOMIZED-PARTITION(a, lo, hi)
3 RANDOMIZED-QUICKSORT(a, lo, p - 1)
4 RANDOMIZED-QUICKSORT(a, p + 1, hi)Correctness is unchanged, since any pivot gives a correct partition. Only the running time is now a random variable, and we want its expectation for every fixed input. This is different from the average case of the deterministic algorithm over random inputs (Worst, Best and Average Case), although, as the first program shows, the two numbers turn out to be equal.
import random
def randomized_quicksort(a, rng):
comparisons = 0
stack = [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi:
continue
r = rng.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
pivot, i = a[hi], lo
for j in range(lo, hi):
comparisons += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
stack.append((lo, i - 1))
stack.append((i + 1, hi))
return comparisons
rng = random.Random(2024)
a = list(range(1000)) # sorted input: the old worst case
print("comparisons on sorted input of 1000, five runs:",
[randomized_quicksort(list(a), rng) for _ in range(5)])
b = list(a); randomized_quicksort(b, rng)
print("sorted correctly:", b == a)comparisons on sorted input of 1000, five runs: [10192, 11131, 10124, 10907, 11134]
sorted correctly: True
Instead of 499,500 comparisons, about 11,000, with some variation from run to run.
Counting comparisons with indicators
The running time is , where is the total number of comparisons in line 4 of the Lomuto loop over the whole run: each partition does constant work plus its comparisons, and there are at most partitions. So it suffices to find .
Name the input values by rank: (assume them distinct). Write for .
Each pair is compared at most once. Every comparison is between a pivot and another element of its subarray, and after the partition the pivot is never part of any later subarray. So
When are and compared? Look at the first moment a pivot is chosen from . Until then, every pivot is either smaller than or larger than , so it sends all of to the same side: the whole set stays together in one subarray. At that first moment there are two cases.
- The pivot is or . Then it is compared with every other element of the subarray, including the other one of the pair: .
- The pivot is some with . Then goes left, goes right, and they are never in the same subarray again: .
The pivot is uniform over the subarray, and the whole of is in that subarray, so each of its elements is equally likely to be the first one chosen from it. Therefore
Neighbours in sorted order () are always compared, which makes sense: nothing else can separate them. The smallest and largest values are compared with probability only .
Adding up. Group the pairs by their distance ; there are pairs at distance :
In the second line, and ; their difference is . Since and , the leading term is : about 39 percent more comparisons than an ideal halving partition would need, the price of picking pivots blindly.
Checking the formula exactly
For small the expectation can be computed exactly. Picking the pivot uniformly from the subarray is equivalent, for distinct keys, to running the deterministic algorithm on a uniformly random permutation (the last element of a random permutation is a uniformly random one of its values, and the subarrays stay uniformly random). So averaging the deterministic algorithm over all permutations gives exactly . The program also checks one pair probability directly.
from fractions import Fraction
from itertools import permutations
from math import factorial
def quicksort_pairs(a):
"""deterministic quicksort (last pivot); returns the set of compared value pairs"""
pairs, stack = [], [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
pivot, i = a[hi], lo
for j in range(lo, hi):
pairs.append((min(a[j], pivot), max(a[j], pivot)))
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
stack += [(lo, i - 1), (i + 1, hi)]
assert len(set(pairs)) == len(pairs) # no pair is compared twice
return pairs
def H(n): return sum(Fraction(1, k) for k in range(1, n + 1))
for n in range(1, 8):
total = sum(len(quicksort_pairs(list(p))) for p in permutations(range(1, n + 1)))
avg = Fraction(total, factorial(n))
print(f"n = {n}: average comparisons {str(avg):>8} 2(n+1)H_n - 4n = {2 * (n + 1) * H(n) - 4 * n}")
n = 6
hits = sum((1, 6) in quicksort_pairs(list(p)) for p in permutations(range(1, 7)))
print(f"Pr[z_1 and z_6 compared] for n = 6: {Fraction(hits, factorial(6))} (formula 2/6 = {Fraction(2, 6)})")n = 1: average comparisons 0 2(n+1)H_n - 4n = 0
n = 2: average comparisons 1 2(n+1)H_n - 4n = 1
n = 3: average comparisons 8/3 2(n+1)H_n - 4n = 8/3
n = 4: average comparisons 29/6 2(n+1)H_n - 4n = 29/6
n = 5: average comparisons 37/5 2(n+1)H_n - 4n = 37/5
n = 6: average comparisons 103/10 2(n+1)H_n - 4n = 103/10
n = 7: average comparisons 472/35 2(n+1)H_n - 4n = 472/35
Pr[z_1 and z_6 compared] for n = 6: 1/3 (formula 2/6 = 1/3)
Every row matches, and the assertion confirms on all runs that no pair is ever compared twice.
Every input costs the same on average
The expectation does not mention the input at all: sorted, reversed and random arrays all have it. The program estimates it on three input shapes for over 30 runs each, and also shows the spread.
import random
def randomized_quicksort(a, rng):
comparisons, stack = 0, [(0, len(a) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi: continue
r = rng.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
pivot, i = a[hi], lo
for j in range(lo, hi):
comparisons += 1
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
stack += [(lo, i - 1), (i + 1, hi)]
return comparisons
n, runs = 2000, 30
H = sum(1 / k for k in range(1, n + 1))
print(f"formula 2(n+1)H_n - 4n = {2 * (n + 1) * H - 4 * n:.0f}")
rng = random.Random(99)
shapes = {"sorted": list(range(n)), "reversed": list(range(n, 0, -1)), "random": rng.sample(range(n), n)}
for name, data in shapes.items():
counts = [randomized_quicksort(list(data), rng) for _ in range(runs)]
print(f"{name:>8}: mean {sum(counts) / runs:8.0f}, min {min(counts)}, max {max(counts)}")formula 2(n+1)H_n - 4n = 24730
sorted: mean 24576, min 22921, max 28702
reversed: mean 24683, min 22315, max 27349
random: mean 25113, min 23158, max 28089
The means agree with the formula to within the sampling noise, whatever the input, and no run strays more than about 20 percent from it. The worst case is still , reached if the random choices happen to pick the maximum every time, but for that has probability about . Deviations of even 50 percent above the mean are already extremely unlikely; tail bounds of this kind are proved in the Randomized Algorithms course.
In C++
The same algorithm with a fixed-seed std::mt19937. The index is drawn as rng() % size, a tiny bias that is irrelevant here and keeps the output identical on every standard library.
#include <cstdio>
#include <random>
#include <utility>
#include <vector>
std::mt19937 rng(2024);
long long comparisons = 0;
int randomized_partition(std::vector<int>& a, int lo, int hi) {
int r = lo + static_cast<int>(rng() % static_cast<unsigned>(hi - lo + 1));
std::swap(a[r], a[hi]);
int pivot = a[hi], i = lo;
for (int j = lo; j < hi; ++j) {
++comparisons;
if (a[j] < pivot) std::swap(a[i++], a[j]);
}
std::swap(a[i], a[hi]);
return i;
}
void randomized_quicksort(std::vector<int>& a, int lo, int hi) {
while (lo < hi) {
int p = randomized_partition(a, lo, hi);
randomized_quicksort(a, lo, p - 1);
lo = p + 1;
}
}
int main() {
const int n = 2000, runs = 50;
double H = 0;
for (int k = 1; k <= n; ++k) H += 1.0 / k;
long long total = 0;
bool ok = true;
for (int run = 0; run < runs; ++run) {
std::vector<int> a(n);
for (int i = 0; i < n; ++i) a[i] = i; // sorted input
comparisons = 0;
randomized_quicksort(a, 0, n - 1);
total += comparisons;
for (int i = 0; i < n; ++i) ok = ok && a[i] == i;
}
std::printf("sorted input, %d runs: mean %.0f comparisons, formula %.0f, sorted: %s\n",
runs, static_cast<double>(total) / runs, 2.0 * (n + 1) * H - 4.0 * n, ok ? "yes" : "no");
}sorted input, 50 runs: mean 24914 comparisons, formula 24730, sorted: yes
Test yourself
In randomized quicksort, with what probability are the -th and -th smallest values () compared?
- for every pair
Why is no pair of elements compared twice by quicksort?
- Because comparisons are cached
- Because every comparison involves the pivot, and the pivot is excluded from all later subarrays
- Because the subarrays are sorted
- Because the pivot is random
What is the leading term of the expected number of comparisons of randomized quicksort?
Randomized quicksort has expected cost for every input. What is its worst-case running time?
- , though with vanishing probability
- unbounded