Sub topic 7
When Quicksort Goes Quadratic
The previous chapter showed that quicksort takes O(n²) time when every partition is as lopsided as possible: one side gets n − 1 elements and the other gets none. This chapter covers which real inputs produce those splits, how to measure the problem, and why it matters beyond speed.
This chapter assumes you know the Lomuto partition and the recursive quicksort from earlier chapters, Big-O notation, and how the Python call stack works.
The pattern behind every bad input
Quicksort's running time depends on where each pivot lands after partitioning. A pivot near the median of its subarray gives balanced splits, about log₂ n levels of recursion, and O(n log n) total work. A pivot that is the smallest or largest element in its subarray removes only itself. The next call then gets n − 1 elements, then n − 2, and so on.
The comparison count is then:
(n − 1) + (n − 2) + … + 1 = n(n − 1) / 2
For n = 1,000 that is 499,500 comparisons. A balanced run needs about 11,000.
Bad behavior does not need every pivot to be extreme. It is enough for a constant fraction of pivots, at every level, to fall within a constant distance of either end of their subarray. In practice, though, the inputs that break a naive quicksort usually make every pivot extreme.
So the question to ask about a pivot strategy is: which inputs make the chosen element an extreme of its subarray, again and again?
Inputs that break a last-element pivot
With the Lomuto scheme and pivot = a[hi], these inputs are the usual culprits.
Already sorted input
In [1, 2, 3, …, n] the last element is the maximum. Every other element is less than it, so the pivot stays at index hi. The left subarray is [1, …, n − 1], which is also sorted, and the pattern repeats all the way down.
Reverse-sorted input
In [n, n − 1, …, 1] the last element is the minimum. Nothing is less than it, so it is swapped to index lo. That swap moves the maximum to the end, so the next call sees the maximum as its pivot. The partitions still shrink by one element per call, so the run is quadratic.
Nearly sorted input
Real data is often almost sorted: log records ordered by timestamp, a sorted table with a few new rows appended, or a list someone sorted last week and then edited. If a sorted array gets one extra element at the end, only the first partition is reasonable. Both sides after it are sorted runs, and each one degrades into a chain. Data like this is common, which is why a fixed end-element pivot is a real hazard.
Many equal keys
Lomuto's loop moves an element left only when a[j] < pivot. When all elements are equal, no element qualifies. The pivot lands at lo, the right side holds n − 1 equal elements, and the run is quadratic. This is the case people most often miss, because the input looks easy. No pivot choice can fix it, since every candidate pivot has the same value. Fixing it requires a different partition, which a later chapter covers.
A milder version also hurts. If an array holds only 0s and 1s, the first partition separates the two values, and then each side is a block of equal keys.
Measuring the damage
The script below runs the Lomuto quicksort with an explicit stack so that it cannot hit Python's recursion limit. It counts comparisons and records the depth the recursion would have reached.
import random
def lomuto_partition_counted(a, lo, hi, counter):
pivot = a[hi]
i = lo
for j in range(lo, hi):
counter[0] += 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 quicksort_counted(a):
counter = [0]
max_depth = 0
stack = [(0, len(a) - 1, 0)] if len(a) > 1 else []
while stack:
lo, hi, depth = stack.pop()
max_depth = max(max_depth, depth)
p = lomuto_partition_counted(a, lo, hi, counter)
if lo < p - 1:
stack.append((lo, p - 1, depth + 1))
if p + 1 < hi:
stack.append((p + 1, hi, depth + 1))
return counter[0], max_depth
n = 1000
inputs = {
"random": random.sample(range(n), n),
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"all equal": [7] * n,
"sorted + 1": list(range(n - 1)) + [n // 2],
}
for name, data in inputs.items():
comparisons, depth = quicksort_counted(data)
assert data == sorted(data)
print(f"{name:>10}: {comparisons:>7} comparisons, max depth {depth}")Typical output:
| Input | Comparisons | Max depth |
|---|---|---|
| random | about 10,000 to 12,000 (varies per run) | around 20 to 25 |
| sorted | 499,500 | 998 |
| reversed | 499,500 | 998 |
| all equal | 499,500 | 998 |
| sorted + 1 | about 250,000 | about 500 |
The sorted, reversed, and all-equal inputs hit n(n − 1)/2 exactly. Doubling n to 2,000 quadruples their comparison counts, while the random case grows only a little more than twofold.
The second failure: stack depth
The depth column shows a problem that is separate from speed. A recursive quicksort makes one nested call per level, so a quadratic run also has O(n) recursion depth. CPython's default recursion limit is 1,000 frames, so the recursive version from earlier crashes on a sorted list of only a few thousand elements, long before it becomes noticeably slow.
import sys
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 quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = lomuto_partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)
print("recursion limit:", sys.getrecursionlimit())
try:
quicksort(list(range(5000)))
except RecursionError as e:
print("RecursionError:", e)In C or C++ the same situation causes a stack overflow, which usually crashes the process instead of raising a catchable exception. Raising the recursion limit only postpones the crash. A later chapter shows how to bound the depth to O(log n) whatever the split quality.
Other pivot rules have their own bad inputs
Changing the pivot rule moves the bad inputs somewhere else. It does not remove them, except in the sense that randomization does (covered later).
| Pivot rule | Inputs that cause quadratic time |
|---|---|
| First element | Sorted, reverse-sorted, nearly sorted |
| Last element | Sorted, reverse-sorted, nearly sorted |
| Middle element | Specially built sequences; sorted input is fine |
| Median of first, middle, last | "Median-of-3 killer" sequences (Musser, 1997) |
| Uniformly random | No fixed bad input; quadratic time only with very small probability |
| Any rule with two-way Lomuto | Many equal keys |
The middle and median-of-three rows matter because every deterministic rule has bad inputs. If the pivot depends only on the positions and values in the array, someone who knows the rule can build an array where each choice lands near an extreme. Musser built such sequences for median-of-three, and that work led to introsort.
Adversarial inputs
M. Douglas McIlroy's 1999 paper "A Killer Adversary for Quicksort" goes further. His program supplies the comparison function to a sort routine and fixes element values lazily, choosing each answer so that the pivot ends up extreme. That technique produces a quadratic input for nearly any deterministic quicksort without reading its source code.
This becomes a security issue when untrusted users control the data. A web service that sorts user-supplied lists with a deterministic quicksort can be slowed down on purpose, which is an algorithmic complexity attack. The same kind of attack has been used against hash tables. The defenses are a random pivot, so the attacker cannot predict the choices, or a sort with a guaranteed worst case. Both appear in later chapters.
Checklist for spotting worst-case risk
- Work out which element the pivot rule picks, and ask what input makes that element the minimum or maximum every time.
- Check whether the partition moves elements equal to the pivot to only one side. If it does, duplicate-heavy data is a risk.
- Ask whether the input could be attacker-controlled. If so, any deterministic pivot rule can be exploited.
- Check whether the implementation recurses without a depth bound. If so, a quadratic case may also crash the program.
Exercise
You run the last-element Lomuto quicksort on an array of 10,000 values in random order, half of them 0 and half 1. Roughly how many comparisons does it make, and why?
Show answer
About 25 million, which is roughly n²/4. The first partition takes about 10,000 comparisons and separates the 0s from the 1s. Each side is then a block of 5,000 equal keys, and Lomuto runs in quadratic time on equal keys: about 5,000²/2 ≈ 12.5 million comparisons per block, so about 25 million in total. A balanced sort would need only a few hundred thousand.
Exercise
Change the pivot rule to pivot = a[lo]: swap a[lo] with a[hi], then run the usual Lomuto partition. Give a 5-element input that causes worst-case behavior, and explain why it does.
Show answer
[1, 2, 3, 4, 5] works, and so does [5, 4, 3, 2, 1]. In sorted input the first element is the minimum of every subarray that the recursion creates, so each partition puts nothing on the left and all remaining elements on the right. That gives 4 + 3 + 2 + 1 = 10 comparisons, which is n(n − 1)/2.
Exercise
The recursive quicksort raises RecursionError on list(range(5000)) in CPython, but quicksortcounted finishes on the same input. Is quicksortcounted fast on that input? What does its result tell you?
Show answer
No. It finishes only because it keeps pending ranges on an explicit list instead of the call stack. It still makes 5000 × 4999 / 2 = 12,497,500 comparisons, and its reported max depth is 4,998. The O(n) depth confirms the partitions are fully lopsided, and that same depth is what overflows the call stack in the recursive version.