Sub topic 9
Randomized Quicksort
This chapter assumes you have read the earlier chapters on the Lomuto partition scheme and on quicksort's best, average, and worst cases. You should be comfortable with Python, recursion, Big-O notation, and basic probability ideas such as expected value.
The previous chapter showed that a fixed pivot rule always has a matching bad input. If you always pick the last element, sorted input is that bad input. Randomized quicksort fixes this by choosing the pivot at random. No single input is then bad every time. The risk depends on the random choices made during the run, not on the order of the data.
The Change: One Random Swap
Randomized quicksort keeps the Lomuto partition function unchanged. Before each partition, it swaps a uniformly random element of the current range into the last position. Lomuto then uses that element as its pivot.
import random
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
def randomized_partition(a, lo, hi):
r = random.randint(lo, hi) # inclusive on both ends
a[r], a[hi] = a[hi], a[r]
return lomuto_partition(a, lo, hi)
def randomized_quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = randomized_partition(a, lo, hi)
randomized_quicksort(a, lo, p - 1)
randomized_quicksort(a, p + 1, hi)
data = list(range(20))
random.shuffle(data)
randomized_quicksort(data)
print(data == list(range(20))) # TrueThe partition logic stays the same, so the correctness argument from the Lomuto chapter still applies. Lomuto is correct for any element placed at a[hi], and the random swap only decides which element that is.
What "Expected O(n log n)" Means
Deterministic quicksort has an average-case bound. That bound averages over all possible input orderings and assumes every ordering is equally likely. Real inputs rarely follow that assumption. Data often arrives already sorted, nearly sorted, or chosen by someone hostile.
Randomized quicksort has an expected bound instead. For every fixed input, the expected running time over the algorithm's own random choices is O(n log n). The probability comes from the coin flips inside the algorithm, not from assumptions about the data. That is a stronger guarantee.
Deriving the Expected Number of Comparisons
Almost all of quicksort's work is comparisons against the pivot, so counting comparisons gives the running time. Assume for now that all keys are distinct. Name them in sorted order as z₁ < z₂ < … < zₙ.
Fact 1: any two elements are compared at most once. Comparisons only happen against the current pivot. After partitioning, the pivot is in its final position and takes no part in later calls.
Fact 2: zᵢ and zⱼ (with i < j) are compared exactly when the first pivot chosen from the set {zᵢ, zᵢ₊₁, …, zⱼ} is zᵢ or zⱼ. As long as no pivot from this set has been picked, all of its members stay together in the same subarray. When the first pivot from the set is picked:
- If it is zᵢ or zⱼ, that element is compared with every other element in its range, including the other endpoint.
- If it is some zₖ strictly between them, zᵢ goes left and zⱼ goes right. They are never in the same call again, so they are never compared.
Each pivot is chosen uniformly from its range. So every one of the j − i + 1 elements in the set is equally likely to be picked first. Two of them lead to a comparison:
P(zᵢ and zⱼ are compared) = 2 / (j − i + 1)
Let X be the total number of comparisons. By linearity of expectation, E[X] is the sum of these probabilities over all pairs. Substitute k = j − i:
E[X] = Σᵢ Σₖ₌₁ⁿ⁻ⁱ 2/(k + 1) < Σᵢ 2·Hₙ = 2n·Hₙ
Here Hₙ = 1 + 1/2 + … + 1/n ≈ ln n is the n-th harmonic number. So E[X] < 2n ln n ≈ 1.39 n log₂ n, which is O(n log n). The exact value is 2(n+1)Hₙ − 4n.
The constant matters in practice. Randomized quicksort makes about 39% more comparisons than the n log₂ n you would get from always splitting perfectly. Its tight inner loop and good cache behavior usually make up for that.
Seeing It Run
The script below counts comparisons on already-sorted input. It compares a fixed last-element pivot with a random pivot. The size n = 500 keeps the fixed-pivot version under Python's default recursion limit of 1000, because that version recurses about n levels deep on sorted input.
import random
comparisons = 0
def partition(a, lo, hi):
global comparisons
pivot = a[hi]
i = 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]
return i
def qsort(a, lo, hi, randomized):
if lo < hi:
if randomized:
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
p = partition(a, lo, hi)
qsort(a, lo, p - 1, randomized)
qsort(a, p + 1, hi, randomized)
def count(n, randomized):
global comparisons
comparisons = 0
a = list(range(n)) # already sorted: worst case for fixed pivot
qsort(a, 0, n - 1, randomized)
assert a == list(range(n))
return comparisons
random.seed(1)
n = 500
print("fixed pivot: ", count(n, randomized=False)) # 124750 = n(n-1)/2
print("random pivot: ", count(n, randomized=True)) # around 4,800; varies by runThe fixed-pivot count is exactly n(n − 1)/2 = 124,750. The randomized count changes from run to run but stays close to the formula value of about 4,800. The chart below plots both curves from the formulas.
How Unlikely Is the Worst Case?
The worst case still exists. If every random choice happens to pick the smallest or largest element in its range, the run takes Θ(n²) time. The probability is tiny. For example, the chance of picking an extreme element at every level on n = 500 distinct keys is (2/500)·(2/499)·…, which is far below anything you will ever observe.
Concentration bounds go further than the expected value. For any constant c, the probability that randomized quicksort takes more than c·n log n time falls polynomially in n as c grows. In practice the running time almost always lands close to its expectation.
Gotchas
Duplicate keys still break it
The analysis above assumed distinct keys. Suppose every element is equal. The test a[j] < pivot is then never true, so the pivot lands at lo and every split has sizes 0 and n − 1. Random choice cannot help when all candidate pivots are the same. The run is quadratic and recurses n levels deep. The chapter on three-way partitioning fixes this case.
Predictable randomness is no randomness
The guarantee depends on the adversary not knowing your random choices. If a server seeds its generator with a constant, or with something an attacker can guess, the attacker can replay the pivot sequence and build an input that triggers the worst case. Use an unpredictable seed for code that sorts input from untrusted sources. Python's default random module seeds itself from OS entropy, but a call to random.seed(42) left over from testing removes that protection.
Off-by-one in the random range
random.randint(lo, hi) includes both endpoints. If you port this code to random.randrange(lo, hi) or to C's rand() % (hi - lo), the last element can never be chosen. Sorting still works, but the choice is no longer uniform and the analysis no longer holds exactly.
Recursion depth is still only bounded in expectation
The expected recursion depth is O(log n). A bad run can still go deeper, so random pivots alone do not guarantee a small stack. A later chapter bounds stack depth to O(log n) without relying on luck.
Random Pivot vs. Shuffling First
An alternative is to shuffle the whole array once with a Fisher–Yates shuffle and then run deterministic quicksort. Both approaches give the same expected bound.
| Approach | Random calls | Guarantee | Notes |
|---|---|---|---|
| Random pivot per partition | About one per partition call | Expected O(n log n) on every input | Drop-in change; also reused by quickselect |
| Shuffle once, then fixed pivot | n − 1 calls up front | Expected O(n log n) on every input | Keeps the sort code deterministic, which can make debugging easier |
| Fixed pivot, no randomness | None | Average case only under random input order | Quadratic on sorted or adversarial input |
Random number generation costs a little, but it is cheap next to the O(n) partition pass it comes before. Many libraries skip it and use deterministic rules such as median-of-three, then add a worst-case fallback. The introsort chapter covers that fallback.
Exercise
In an array of 10 distinct keys sorted as z1 < … < z10, what is the probability that randomized quicksort ever compares z3 with z7? What about z3 with z4?
Show answer
The set {z3, …, z7} has 5 elements, so the probability is 2/5 = 0.4. For z3 and z4 the set has 2 elements, so the probability is 2/2 = 1. Adjacent keys are always compared, because nothing between them can separate them.
Exercise
A teammate says "randomized quicksort has the same average-case bound as ordinary quicksort, so randomizing adds nothing." Explain what is wrong with this claim.
Show answer
Ordinary quicksort's O(n log n) average assumes every input ordering is equally likely. Real data, such as sorted input or adversarial input, breaks that assumption. Randomized quicksort's O(n log n) expectation holds for every fixed input, because the randomness comes from the algorithm itself. Randomizing turns an assumption about the data into a guarantee.
Exercise
Run the comparison-counting script with the input changed to [7] * 500 and randomized=True. Roughly how many comparisons do you expect, and why?
Show answer
About 124,750, which is n(n-1)/2. With all keys equal, a[j] < pivot is never true, so every partition puts the pivot at lo and leaves n-1 elements on one side, no matter which index is chosen at random. Three-way partitioning fixes this.