TExcelTAD
Home › Sorting & Order Statistics › Randomized Quicksort and Its Expected Cost

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 2nln⁡n≈1.39 nlg⁡n2n \ln n \approx 1.39\, n \lg n 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.

text
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.

python · try it yourself
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 O(n+X)O(n + X), where XX 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 nn partitions. So it suffices to find E[X]\mathbb{E}[X].

Name the input values by rank: z1<z2<⋯<znz_1 < z_2 < \cdots < z_n (assume them distinct). Write Zij={zi,zi+1,…,zj}Z_{ij} = \{z_i, z_{i+1}, \ldots, z_j\} for i<ji < j.

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

X=∑i=1n−1∑j=i+1nXij,Xij=I{zi is compared with zj}.X = \sum_{i=1}^{n-1} \sum_{j=i+1}^{n} X_{ij}, \qquad X_{ij} = I\{z_i \text{ is compared with } z_j\}.

When are ziz_i and zjz_j compared? Look at the first moment a pivot is chosen from ZijZ_{ij}. Until then, every pivot is either smaller than ziz_i or larger than zjz_j, so it sends all of ZijZ_{ij} to the same side: the whole set stays together in one subarray. At that first moment there are two cases.

  • The pivot is ziz_i or zjz_j. Then it is compared with every other element of the subarray, including the other one of the pair: Xij=1X_{ij} = 1.
  • The pivot is some zkz_k with i<k<ji < k < j. Then ziz_i goes left, zjz_j goes right, and they are never in the same subarray again: Xij=0X_{ij} = 0.

The pivot is uniform over the subarray, and the whole of ZijZ_{ij} is in that subarray, so each of its j−i+1j - i + 1 elements is equally likely to be the first one chosen from it. Therefore

Pr⁡[Xij=1]=2j−i+1.\Pr[X_{ij} = 1] = \frac{2}{j - i + 1}.

Neighbours in sorted order (j=i+1j = i + 1) are always compared, which makes sense: nothing else can separate them. The smallest and largest values are compared with probability only 2n\frac{2}{n}.

Adding up. Group the pairs by their distance k=j−ik = j - i; there are n−kn - k pairs at distance kk:

E[X]=∑i<j2j−i+1=∑k=1n−12(n−k)k+1=2(n+1)Hn−4nrewrite n−k=(n+1)−(k+1)<2nHn=2nln⁡n+O(n)=O(nlg⁡n).\begin{aligned} \mathbb{E}[X] &= \sum_{i<j} \frac{2}{j - i + 1} = \sum_{k=1}^{n-1} \frac{2(n - k)}{k + 1} \\ &= 2(n + 1) H_n - 4n && \text{rewrite } n - k = (n + 1) - (k + 1) \\ &< 2 n H_n = 2n \ln n + O(n) = O(n \lg n). \end{aligned}

In the second line, ∑k=1n−12(n+1)k+1=2(n+1)(Hn−1)\sum_{k=1}^{n-1} \frac{2(n+1)}{k+1} = 2(n+1)(H_n - 1) and ∑k=1n−12=2(n−1)\sum_{k=1}^{n-1} 2 = 2(n-1); their difference is 2(n+1)Hn−4n2(n+1)H_n - 4n. Since Hn=ln⁡n+O(1)H_n = \ln n + O(1) and 2ln⁡n=(2ln⁡2)lg⁡n2 \ln n = (2 \ln 2) \lg n, the leading term is 1.386 nlg⁡n1.386\, n \lg n: about 39 percent more comparisons than an ideal halving partition would need, the price of picking pivots blindly.

Checking the formula exactly

For small nn 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 n!n! permutations gives exactly E[X]\mathbb{E}[X]. The program also checks one pair probability directly.

python · try it yourself
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 1+2+6+⋯+50401 + 2 + 6 + \cdots + 5040 runs that no pair is ever compared twice.

Every input costs the same on average

The expectation 2(n+1)Hn−4n2(n+1)H_n - 4n does not mention the input at all: sorted, reversed and random arrays all have it. The program estimates it on three input shapes for n=2000n = 2000 over 30 runs each, and also shows the spread.

python · try it yourself
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 Θ(n2)\Theta(n^2), reached if the random choices happen to pick the maximum every time, but for n=2000n = 2000 that has probability about 12000!\frac{1}{2000!}. 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.

cpp · try it yourself
#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 ii-th and jj-th smallest values (i<ji < j) compared?

  1. 1j−i\frac{1}{j - i}
  2. 2j−i+1\frac{2}{j - i + 1}
  3. 1n\frac{1}{n}
  4. 2n\frac{2}{n} for every pair

Why is no pair of elements compared twice by quicksort?

  1. Because comparisons are cached
  2. Because every comparison involves the pivot, and the pivot is excluded from all later subarrays
  3. Because the subarrays are sorted
  4. Because the pivot is random

What is the leading term of the expected number of comparisons of randomized quicksort?

  1. nlg⁡nn \lg n
  2. 2nln⁡n≈1.39 nlg⁡n2 n \ln n \approx 1.39\, n \lg n
  3. n2/4n^2 / 4
  4. 2nlg⁡n2 n \lg n

Randomized quicksort has expected cost O(nlg⁡n)O(n \lg n) for every input. What is its worst-case running time?

  1. O(nlg⁡n)O(n \lg n)
  2. Θ(n2)\Theta(n^2), though with vanishing probability
  3. Θ(n)\Theta(n)
  4. unbounded