TExcelTAD
Home › Sorting & Order Statistics › Quicksort: Worst, Best and Balanced Splits

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

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

python · try it yourself
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 m=hi−lo+1m = hi - lo + 1 (Proving Recursive Algorithms Correct by Induction). Lengths 0 and 1 are sorted already. For m≥2m \ge 2, the partition leaves smaller values left of pp and the rest right of it; both sides are shorter than mm, 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 mm elements takes Θ(m)\Theta(m) time (exactly m−1m - 1 comparisons). If the pivot lands at relative position qq, the two sides have qq and m−1−qm - 1 - q elements, so

T(n)=T(q)+T(n−1−q)+Θ(n),0≤q≤n−1.T(n) = T(q) + T(n - 1 - q) + \Theta(n), \qquad 0 \le q \le n - 1.

Everything depends on qq.

The worst case: one side empty

If every partition puts the pivot at an end, one side is empty and the other has n−1n - 1 elements:

T(n)=T(n−1)+T(0)+Θ(n)=∑m=1nΘ(m)=Θ(n2).T(n) = T(n - 1) + T(0) + \Theta(n) = \sum_{m=1}^{n} \Theta(m) = \Theta(n^2).

Counting comparisons exactly, the partitions cost (n−1)+(n−2)+⋯+1=n(n−1)2(n-1) + (n-2) + \cdots + 1 = \frac{n(n-1)}{2}. 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 W(n)W(n) be the worst-case number of comparisons. Then W(n)=max⁡0≤q≤n−1(W(q)+W(n−1−q))+n−1W(n) = \max_{0 \le q \le n-1} \bigl(W(q) + W(n-1-q)\bigr) + n - 1. Guess W(n)≤n2/2W(n) \le n^2/2 and use the substitution method:

W(n)≤max⁡qq2+(n−1−q)22+n−1induction hypothesis=(n−1)22+n−1a convex function peaks at an end, q=0=n2−12≤n22.\begin{aligned} W(n) &\le \max_{q} \frac{q^2 + (n-1-q)^2}{2} + n - 1 && \text{induction hypothesis} \\ &= \frac{(n-1)^2}{2} + n - 1 && \text{a convex function peaks at an end, } q = 0 \\ &= \frac{n^2 - 1}{2} \le \frac{n^2}{2}. \end{aligned}

So W(n)=O(n2)W(n) = O(n^2), and the sorted input shows W(n)=Ω(n2)W(n) = \Omega(n^2): the worst case is Θ(n2)\Theta(n^2).

The best case: halves

If every pivot lands in the middle, both sides have at most n/2n/2 elements and

T(n)≤2T(n/2)+Θ(n)=Θ(nlg⁡n)T(n) \le 2T(n/2) + \Theta(n) = \Theta(n \lg n)

by case 2 of the master theorem. The best case is also Ω(nlg⁡n)\Omega(n \lg n); 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 99 to 11: T(n)=T(n/10)+T(9n/10)+cnT(n) = T(n/10) + T(9n/10) + cn. In the recursion tree each level costs at most cncn (the subarrays on one level are disjoint), the shortest root-to-leaf path has log⁡10n\log_{10} n levels and the longest log⁡10/9n\log_{10/9} n. So

T(n)≤cnlog⁡10/9n=clg⁡(10/9) nlg⁡n≈6.58 c nlg⁡n=O(nlg⁡n).T(n) \le cn \log_{10/9} n = \frac{c}{\lg(10/9)}\, n \lg n \approx 6.58\, c\, n \lg n = O(n \lg n).

The same holds for any constant proportion, 9999 to 11 included; only the constant grows. The program computes the exact comparison count for fixed splits by recurrence and divides by nlg⁡nn \lg n. A ratio that levels off means Θ(nlg⁡n)\Theta(n \lg n); the one-sided split grows without bound.

python · try it yourself
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 1:91 : 9 row tends to about 2.132.13, the reciprocal of 0.1lg⁡10+0.9lg⁡109≈0.4690.1 \lg 10 + 0.9 \lg \frac{10}{9} \approx 0.469, far below the crude bound 6.586.58 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 3.43.4 per column, as n2/(nlg⁡n)=n/lg⁡nn^2 / (n \lg n) = n / \lg n should when nn 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 Θ(n)+Θ(n−1)=Θ(n)\Theta(n) + \Theta(n - 1) = \Theta(n) and leave two halves of about (n−1)/2(n-1)/2, 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 O(nlg⁡n)O(n \lg n) 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 nn levels deep and exceed Python's recursion limit.

python · try it yourself
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 n(n−1)2\frac{n(n-1)}{2} 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.

cpp · try it yourself
#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 Θ(n2)\Theta(n^2) time on sorted input?

  1. Because each partition swaps every element
  2. Because the pivot is the maximum each time, so one side is empty and the other has n−1n - 1 elements
  3. Because the recursion depth is lg⁡n\lg n
  4. Because sorted input has many inversions

If every partition split 9999 to 11, quicksort's running time would be...

  1. Θ(n2)\Theta(n^2)
  2. Θ(nlg⁡n)\Theta(n \lg n) with a larger constant
  3. Θ(n)\Theta(n)
  4. Θ(n1.5)\Theta(n^{1.5})

In the worst-case proof, why is max⁡q(q2+(n−1−q)2)\max_q \bigl(q^2 + (n-1-q)^2\bigr) attained at q=0q = 0 or q=n−1q = n - 1?

  1. Because the expression is convex in qq, so its maximum on an interval is at an endpoint
  2. Because qq must be even
  3. Because the middle value q=(n−1)/2q = (n-1)/2 is the maximum
  4. Because the expression is constant

What does the correctness proof of quicksort use as its induction measure?

  1. the value of the pivot
  2. the length of the subarray, with strong induction
  3. the number of swaps
  4. the recursion depth, counting down