Quicksort: Worst, Best and Balanced Splits
With a partition procedure in hand, quicksort is three lines: partition, then sort each side. Its running time depends entirely on where the pivot lands. If it always lands near the middle, quicksort is as fast as merge sort. If it always lands at an end, quicksort is as slow as insertion sort, and the classic way to get there is to hand it an input that is already sorted. This lesson works out both extremes and the large middle ground between them, using the recurrence tools from Writing Recurrences and Recursion Trees.
The algorithm
QUICKSORT(a, lo, hi) // sorts a[lo..hi] inclusive
1 if lo < hi
2 p = LOMUTO-PARTITION(a, lo, hi)
3 QUICKSORT(a, lo, p - 1)
4 QUICKSORT(a, p + 1, hi)The whole array is sorted by QUICKSORT(a, 0, n - 1). Here is the full run on the array from Lomuto Partitioning:
The Python version prints one line per call that does work, in the same order as the animation: the "Partition … around pivot …" frames with the pivot's final position, and the "… alone is in place" frames for one-element subarrays.
def partition(a, lo, hi):
pivot, i = a[hi], 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 quicksort(a, lo, hi, depth=0):
if lo > hi:
return
pad = " " * depth
if lo == hi:
print(f"{pad}{a[lo]} alone is in place")
return
pivot = a[hi]
p = partition(a, lo, hi)
print(f"{pad}partition {lo}..{hi} around pivot {pivot}: it lands at {p} {a}")
quicksort(a, lo, p - 1, depth + 1)
quicksort(a, p + 1, hi, depth + 1)
a = [6, 3, 8, 1, 9, 2, 5]
quicksort(a, 0, len(a) - 1)
print(a)partition 0..6 around pivot 5: it lands at 3 [3, 1, 2, 5, 9, 8, 6]
partition 0..2 around pivot 2: it lands at 1 [1, 2, 3, 5, 9, 8, 6]
1 alone is in place
3 alone is in place
partition 4..6 around pivot 6: it lands at 4 [1, 2, 3, 5, 6, 8, 9]
partition 5..6 around pivot 9: it lands at 6 [1, 2, 3, 5, 6, 8, 9]
8 alone is in place
[1, 2, 3, 5, 6, 8, 9]
Correctness is a strong induction on the length (Proving Recursive Algorithms Correct by Induction). Lengths 0 and 1 are sorted already. For , the partition leaves smaller values left of and the rest right of it; both sides are shorter than , so by the induction hypothesis the recursive calls sort them, and a sorted left part, then the pivot, then a sorted right part, is sorted.
The cost recurrence
Partitioning elements takes time (exactly comparisons). If the pivot lands at relative position , the two sides have and elements, so
Everything depends on .
The worst case: one side empty
If every partition puts the pivot at an end, one side is empty and the other has elements:
Counting comparisons exactly, the partitions cost . This happens with the last-element pivot whenever the input is already sorted (the pivot is the maximum each time) or sorted in reverse (the minimum each time), and with Lomuto's < whenever all keys are equal.
That this really is the worst case needs a short argument, because other splits might conceivably be worse. Let be the worst-case number of comparisons. Then . Guess and use the substitution method:
So , and the sorted input shows : the worst case is .
The best case: halves
If every pivot lands in the middle, both sides have at most elements and
by case 2 of the master theorem. The best case is also ; the comparison lower bound in Decision Trees shows no comparison sort can do better.
Unbalanced but proportional splits are still fine
Quicksort does not need perfect halves. Suppose every partition splits to : . In the recursion tree each level costs at most (the subarrays on one level are disjoint), the shortest root-to-leaf path has levels and the longest . So
The same holds for any constant proportion, to included; only the constant grows. The program computes the exact comparison count for fixed splits by recurrence and divides by . A ratio that levels off means ; the one-sided split grows without bound.
import math
def comparisons(n, small_fraction):
"""exact comparison count when every partition sends floor(small_fraction * size) elements left"""
T = [0] * (n + 1)
for m in range(2, n + 1):
q = math.floor(small_fraction * (m - 1))
T[m] = T[q] + T[m - 1 - q] + (m - 1)
return T
n = 20000
for name, frac in [("1 : 1", 0.5), ("1 : 3", 0.25), ("1 : 9", 0.1), ("1 : 99", 0.01), ("0 : 1", 0.0)]:
T = comparisons(n, frac)
row = " ".join(f"{T[m] / (m * math.log2(m)):7.2f}" for m in [1250, 5000, 20000])
print(f"split {name:>6}: T(n) / (n lg n) at n = 1250, 5000, 20000: {row}")split 1 : 1: T(n) / (n lg n) at n = 1250, 5000, 20000: 0.81 0.84 0.87
split 1 : 3: T(n) / (n lg n) at n = 1250, 5000, 20000: 1.01 1.05 1.07
split 1 : 9: T(n) / (n lg n) at n = 1250, 5000, 20000: 1.72 1.79 1.83
split 1 : 99: T(n) / (n lg n) at n = 1250, 5000, 20000: 8.67 8.70 9.62
split 0 : 1: T(n) / (n lg n) at n = 1250, 5000, 20000: 60.70 203.41 699.87
The proportional rows creep up only slowly. The row tends to about , the reciprocal of , far below the crude bound from the longest path, because most leaves of the tree are much shallower than the deepest one. The one-sided split, the worst case, grows by a factor of about per column, as should when is multiplied by 4.
Good and bad splits mixed
Real inputs give a mixture. Suppose bad and good splits alternate: a partition that peels off one element, then one that splits evenly. Two levels then cost and leave two halves of about , which is the same as one good split at twice the cost. The bad split is absorbed into the good one, and the total is still with a larger constant. This is the intuition for why quicksort is fast on average: a constant fraction of good splits is all it needs. The next lesson, Randomized Quicksort and Its Expected Cost, turns that intuition into an exact formula.
Measuring input shapes
Deterministic quicksort (last element as pivot) on four input shapes. The implementation uses an explicit stack instead of recursion, because a sorted input would recurse levels deep and exceed Python's recursion limit.
import math, random
def quicksort_count(a):
a = list(a)
comparisons = 0
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):
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))
assert a == sorted(a)
return comparisons
n = 1000
rng = random.Random(8)
shapes = {
"random": rng.sample(range(n), n),
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"few distinct": [rng.randint(0, 4) for _ in range(n)],
}
print(f"n = {n}: n(n-1)/2 = {n * (n - 1) // 2}, n lg n = {n * math.log2(n):.0f}")
for name, data in shapes.items():
print(f"{name:>12}: {quicksort_count(data):>7} comparisons")n = 1000: n(n-1)/2 = 499500, n lg n = 9966
random: 10873 comparisons
sorted: 499500 comparisons
reversed: 499500 comparisons
few distinct: 102236 comparisons
Sorted and reversed inputs hit exactly. With only five distinct values the cost is also quadratic, because after the first few partitions every subarray consists of equal keys. Only the random input is fast.
In C++
The same deterministic quicksort with a comparison counter. The "random" input is a Fisher-Yates shuffle driven by a fixed-seed std::mt19937, whose output sequence the C++ standard fixes exactly.
#include <cstdio>
#include <random>
#include <utility>
#include <vector>
long long comparisons = 0;
int partition(std::vector<int>& a, int lo, int 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 quicksort(std::vector<int>& a, int lo, int hi) {
while (lo < hi) { // recurse on the left, loop on the right
int p = partition(a, lo, hi);
quicksort(a, lo, p - 1);
lo = p + 1;
}
}
int main() {
const int n = 1000;
std::vector<int> sorted(n), shuffled(n);
for (int i = 0; i < n; ++i) sorted[i] = shuffled[i] = i;
std::mt19937 rng(8);
for (int i = n - 1; i > 0; --i) std::swap(shuffled[i], shuffled[rng() % (i + 1)]);
comparisons = 0;
quicksort(sorted, 0, n - 1);
std::printf("sorted input: %lld comparisons\n", comparisons);
comparisons = 0;
quicksort(shuffled, 0, n - 1);
std::printf("shuffled input: %lld comparisons\n", comparisons);
}sorted input: 499500 comparisons
shuffled input: 10675 comparisons
Test yourself
With the last element as pivot, why does quicksort take time on sorted input?
- Because each partition swaps every element
- Because the pivot is the maximum each time, so one side is empty and the other has elements
- Because the recursion depth is
- Because sorted input has many inversions
If every partition split to , quicksort's running time would be...
- with a larger constant
In the worst-case proof, why is attained at or ?
- Because the expression is convex in , so its maximum on an interval is at an endpoint
- Because must be even
- Because the middle value is the maximum
- Because the expression is constant
What does the correctness proof of quicksort use as its induction measure?
- the value of the pivot
- the length of the subarray, with strong induction
- the number of swaps
- the recursion depth, counting down