Sub topic 7
When Quicksort Goes Quadratic
This chapter assumes you have read the earlier chapters on the Lomuto partition scheme and the average-case analysis. You should also be comfortable with recursion and Big-O notation. Here we look at the inputs that push quicksort to O(n²) time, and at why those inputs are common in real data.
The shape of a bad split
Quicksort is fast when each partition splits the range into two parts of similar size. It is slow when one side is empty every time. If the pivot is always the smallest or largest element in the range, each call removes only the pivot. The next call then works on n − 1 elements.
The cost follows this recurrence:
T(n) = T(n − 1) + (n − 1)
Summing it gives (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 comparisons, which is O(n²). The recursion depth also grows to n, which matters in languages with a limited call stack.
Which inputs trigger it
The bad inputs depend on the pivot rule. With the last-element pivot and the Lomuto partition scheme, three inputs that are easy to come by all lead to quadratic time:
| Pivot rule | Inputs that cause O(n²) |
|---|---|
| Last element (Lomuto) | Sorted, reverse-sorted, all keys equal |
| First element | Sorted, reverse-sorted, all keys equal |
| Middle element | Specially built "killer" sequences; sorted input is fine |
The all-equal case surprises many people. Lomuto moves an element to the left side only when a[j] < pivot, so when every key equals the pivot, the left side stays empty. The pivot lands at index lo and the right side holds everything else.
Sorted and nearly sorted data shows up all the time in practice: log files ordered by timestamp, lists that were sorted before and then had one new item appended, or database results already returned in order. A fixed-position pivot is therefore a real risk in production code.
Measuring it
The program below counts comparisons for four inputs of size 500:
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, lo, hi, counter):
if lo < hi:
p = lomuto_partition_counted(a, lo, hi, counter)
quicksort_counted(a, lo, p - 1, counter)
quicksort_counted(a, p + 1, hi, counter)
n = 500
inputs = {
"random": random.sample(range(n), n),
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
"all equal": [7] * n,
}
for name, data in inputs.items():
counter = [0]
quicksort_counted(data, 0, len(data) - 1, counter)
print(f"{name:10} {counter[0]:>7}")The random input takes about 5,000 to 6,000 comparisons. The exact count changes from run to run. Each of the other three inputs takes exactly 124,750, which is 500 × 499 / 2.
What this means for the design
The pivot rule decides which inputs are dangerous. A fixed position makes the bad inputs easy to predict, both for ordinary data and for an attacker who sends crafted input to a server. The next chapters cover the fixes: better pivot choices, randomization, and three-way partitioning for repeated keys.
Exercise
Using the Lomuto quicksort with a last-element pivot, how many comparisons does it make on the list [4, 4, 4, 4, 4, 4, 4, 4], and why?
Show answer
28. No element is strictly less than the pivot, so every partition puts the pivot at index lo and leaves the other n − 1 elements on the right. The counts are 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28, which equals 8 × 7 / 2.
Exercise
A middle-element pivot handles sorted input well. Does that make it safe from quadratic behavior?
Show answer
No. With a middle-element pivot, sorted input splits evenly, but an adversary can still build sequences that place the smallest or largest remaining value in the middle position at every step. Any pivot rule that is fixed and known in advance has some O(n²) input.