Sub topic 6
How Fast Is Quicksort? Best, Average, and Worst Case
This chapter works out how many operations quicksort performs. It assumes you know Big-O notation and recursion, and that you have read the earlier chapters on the Lomuto partition and recursive quicksort. The analysis uses that version: the last element is the pivot, and the keys are distinct. Duplicate keys get their own chapter later.
The cost model: count comparisons
The analysis counts key comparisons, the a[j] < pivot tests inside the partition loop. Swaps, index updates, and function calls each happen at most a constant number of times per comparison, so the comparison count sets the Big-O running time.
Partitioning a subarray of m elements compares every non-pivot element with the pivot exactly once. That is m - 1 comparisons. After partitioning, the pivot sits at its final position, with k elements to its left and m - 1 - k to its right. The cost of quicksort on n elements is therefore:
T(n) = T(k) + T(n - 1 - k) + (n - 1)
T(0) = T(1) = 0The value of k depends on where the pivot ranks among the elements, and that rank decides every case below.
Best case: balanced splits
In the best case, every pivot is the median, so k is about n/2 and the recurrence becomes:
T(n) ≈ 2·T(n/2) + nA recursion tree shows the result. The root does about n comparisons. Its two children each work on n/2 elements, so together they also do about n. Each level of the tree does about n work in total, and the subarray size halves at each level, so there are about log₂ n levels.
The best case is Θ(n log n). Any comparison sort needs Ω(n log n) comparisons in the worst case, so quicksort's best case is optimal apart from the constant factor.
Splits do not have to be even
Perfect medians are not required. Suppose every partition splits 9 to 1. The longest path in the tree follows the 9/10 side, so its depth is log_{10/9} n, which is about 6.6 · log₂ n. Every level still costs at most n. The total is still O(n log n), with a larger constant. This holds for any fixed fraction, and it explains why quicksort does well even with pivots that are only roughly central.
Worst case: one side is empty
The worst case happens when every pivot is the smallest or largest element of its subarray. Then k = 0 (or n - 1) at every step:
T(n) = T(n - 1) + (n - 1)
= (n - 1) + (n - 2) + ... + 1
= n(n - 1) / 2That is Θ(n²). The recursion tree degenerates into a path of depth n. Each call removes only the pivot. With the last-element pivot, an already sorted array triggers this case. The next chapter catalogs which inputs cause it and why.
The recursion depth is n as well. Each pending call uses a stack frame, so a large sorted input can also overflow the call stack. A later chapter shows how to bound that depth.
Average case: the derivation
"Average" here means the expected cost when the input is a uniformly random permutation of distinct keys. With that assumption, the pivot's rank is equally likely to be any value from 0 to n−1. Randomized quicksort, covered later, gives the same distribution on any input by choosing the pivot at random.
Method 1: count which pairs get compared
Name the elements in sorted order z₁ < z₂ < ... < zₙ. Two observations do the work:
- Two elements are compared only when one of them is the current pivot. After that, the pivot is never compared again, so any pair is compared at most once.
zᵢandzⱼ(withi < j) stay in the same subarray until a pivot is chosen from the rangezᵢ, zᵢ₊₁, ..., zⱼ. If that first pivot is some element strictly between them, it sends them to opposite sides and they are never compared. If it iszᵢorzⱼ, they are compared.
Each of the j - i + 1 elements in that range is equally likely to be the first one picked, so:
P(zᵢ and zⱼ are compared) = 2 / (j - i + 1)Expected comparisons are the sum of these probabilities over all pairs:
E[C(n)] = Σ_{i<j} 2/(j - i + 1)
= Σ_{i=1}^{n-1} Σ_{d=1}^{n-i} 2/(d + 1)
< Σ_{i=1}^{n} 2·Hₙ
= 2n·HₙHere Hₙ = 1 + 1/2 + ... + 1/n ≈ ln n is the n-th harmonic number. The average case is therefore O(n log n).
Method 2: solve the recurrence exactly
Averaging the recurrence over all n pivot ranks gives:
C(n) = (n - 1) + (1/n) · Σ_{k=0}^{n-1} [C(k) + C(n-1-k)]
= (n - 1) + (2/n) · Σ_{k=0}^{n-1} C(k)Multiply by n, subtract the same equation written for n - 1, and divide by n(n + 1). The sum collapses, and the result is a closed form:
C(n) = 2(n + 1)·Hₙ - 4nYou can check small cases: C(1) = 0, C(2) = 1, C(3) = 8/3. Since Hₙ ≈ ln n, the leading term is 2n ln n ≈ 1.39 · n log₂ n. On average, quicksort does about 39% more comparisons than the perfectly balanced best case.
Checking the math by experiment
The script below counts comparisons for random inputs and for a sorted input, then compares the counts with the formulas.
import math
import random
def count_comparisons(a):
count = 0
def partition(lo, hi):
nonlocal count
pivot = a[hi]
i = lo
for j in range(lo, hi):
count += 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 sort(lo, hi):
if lo < hi:
p = partition(lo, hi)
sort(lo, p - 1)
sort(p + 1, hi)
sort(0, len(a) - 1)
return count
def expected_comparisons(n):
h = sum(1 / k for k in range(1, n + 1))
return 2 * (n + 1) * h - 4 * n
random.seed(1)
n = 400
trials = [count_comparisons(random.sample(range(n), n)) for _ in range(200)]
print("random avg :", sum(trials) / len(trials))
print("formula :", round(expected_comparisons(n), 1))
print("n log2 n :", round(n * math.log2(n), 1))
print("sorted :", count_comparisons(list(range(n))))
print("n(n-1)/2 :", n * (n - 1) // 2)The random average comes out close to the formula's 3669. The sorted input gives exactly 79800, which is n(n-1)/2. That is more than 20 times the average. The sorted run recurses about 400 levels deep, which is below Python's default limit of 1000. Try n = 2000 and it raises RecursionError.
The chart plots expected comparisons against worst-case comparisons as n doubles.
Summary of the cases
| Case | Split at each level | Comparisons | Time | Stack depth |
|---|---|---|---|---|
| Best | Median pivot, n/2 : n/2 | ≈ n log₂ n | Θ(n log n) | Θ(log n) |
| Average (random order) | Pivot rank uniform | 2(n+1)Hₙ − 4n ≈ 1.39 n log₂ n | Θ(n log n) | Θ(log n) expected |
| Constant-fraction | e.g. 9 : 1 every time | c · n log n | Θ(n log n) | Θ(log n) |
| Worst | 0 : n−1 every time | n(n−1)/2 | Θ(n²) | Θ(n) |
Why quicksort is fast in practice
Mergesort does fewer comparisons in the worst case. Quicksort's average is still often faster in practice. Its inner loop is a single comparison and an occasional swap over contiguous memory, which suits CPU caches well, and it needs no auxiliary array. Big-O hides these constant factors. The 1.39 factor in comparisons is usually outweighed by cheaper work per comparison.
Exercises
Exercise
Every partition in some run of quicksort splits its subarray 3 : 1, with three quarters on one side. What are the time complexity and the approximate recursion depth, as a function of n?
Show answer
Each level of the recursion tree costs at most n comparisons. The deepest path follows the 3/4 side, so the depth is log_{4/3} n ≈ 2.41 · log₂ n. The total is O(n log n), and the depth is Θ(log n).
Exercise
Use the pair-counting argument to find the probability that the smallest and largest elements (z₁ and zₙ) are ever compared. What is the probability for two adjacent elements zᵢ and zᵢ₊₁?
Show answer
For z₁ and zₙ the range contains all n elements, so the probability is 2/n: they are compared only if one of them is the very first pivot. Adjacent elements have a range of size 2, so the probability is 2/2 = 1. Adjacent elements are always compared, because no element lies between them to separate them.
Exercise
Use the closed form C(n) = 2(n+1)Hₙ − 4n to compute the expected comparisons for n = 4. Then confirm the result with the recurrence C(n) = (n−1) + (2/n)·Σ C(k).
Show answer
H₄ = 25/12, so C(4) = 2·5·25/12 − 16 = 250/12 − 16 = 29/6 ≈ 4.83. With the recurrence, C(0)=0, C(1)=0, C(2)=1, C(3)=8/3, so C(4) = 3 + (2/4)(0 + 0 + 1 + 8/3) = 3 + 11/6 = 29/6. The two results match.