Quicksort
Quicksort picks a pivot, moves smaller items to its left and larger ones to its right, then sorts each side; it averages O(n log n) in place, but with the first item as pivot sorted input degenerates to O(n²), which median-of-three or a random pivot fixes.
Quicksort is one of the fastest comparison sorts in practice: C's qsort, C++'s std::sort and Java's sort for int arrays are all quicksort at heart. On average it is O(n log n), in place, with small constants. But it has a famous trap: with a badly chosen pivot, input that is already sorted is the slowest, 1000 numbers taking nearly 500,000 comparisons; and in Python things break even sooner, since the recursion goes 1000 levels deep and runs straight into the recursion limit. This lesson writes the easiest version first, then the in-place version, then counts that trap and fixes it.
The three-line version: clear at a glance
Pick one number as the pivot, say the first. Of the rest, put those smaller than the pivot in one pile and those not smaller in another. Sort each pile, put the pivot between them, and it is sorted. Written with list comprehensions, it is almost that sentence:
1def quick_sort(a):2 if len(a) <= 1:3 return a4 p, rest = a[0], a[1:]5 return quick_sort([x for x in rest if x < p]) + [p] + quick_sort([x for x in rest if x >= p])6 7print(quick_sort([4, 7, 2, 6, 1, 5, 3]))8print(quick_sort([3, 1, 3, 2, 3]))9print(quick_sort([]))
[1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 3, 3] []
In the figure, the arrows down are calls, and the dashed arrows up are returns.
1def quick_sort(a):2 if len(a) <= 1:3 return a4 p, rest = a[0], a[1:]5 return quick_sort([x for x in rest if x < p]) + [p] + quick_sort([x for x in rest if x >= p])
Easy to read, but it costs:
- Not in place: each call makes
rest, the two piles, and two more lists for the+joins. - Scans rest twice per level: the two comprehensions each walk it from the start, doubling the comparisons.
- Everything equal to the pivot lands in the right pile, which slows it down when there are many duplicates.
1made = 02cmps = 03 4def quick_sort(a):5 global made, cmps6 if len(a) <= 1:7 return a8 p, rest = a[0], a[1:]9 smaller = [x for x in rest if x < p]10 larger = [x for x in rest if x >= p]11 made += 3 # rest, smaller, larger (the joins not counted)12 cmps += 2 * len(rest) # each comprehension compares once per item13 return quick_sort(smaller) + [p] + quick_sort(larger)14 15data = [(i * 7919) % 10007 for i in range(1024)]16result = quick_sort(data)17print(result == sorted(data), "comparisons", cmps, "new lists", made)
True comparisons 21554 new lists 1893
The three-line version sorts [3, 1, 4, 1, 5]. On the first level, with 3 as pivot, what are the two piles?
[1, 4, 1, 5]. The ones smaller than 3, in their original order, are 1, 1; the ones not smaller are 4, 5. The pivot 3 goes in neither pile; it ends up between them.Partitioning in place
The in-place version makes no new lists: it swaps within the stretch a[lo..hi], moving the small items to the left. The most common way is Lomuto partitioning: the pivot is the stretch's last item, p = a[hi]; i points at "where the next item smaller than p goes"; j scans left to right, and each time it meets an item smaller than p, swaps it with a[i] and moves i one right. After the scan, a[lo..i-1] are all smaller than p, and the pivot is swapped into a[i].
1def partition(a, lo, hi):2 p = a[hi]3 i = lo4 for j in range(lo, hi):5 if a[j] < p:6 a[i], a[j] = a[j], a[i]7 i += 18 a[i], a[hi] = a[hi], a[i]9 return i
The other way is Hoare partitioning: two pointers walk in from both ends and swap when the left one finds a large item and the right one a small one. It swaps less than Lomuto, but its edges are harder to get right; in an interview Lomuto is enough.
One Lomuto partition around the last item, 4. What does it print?
1def partition(a, lo, hi):2 p = a[hi]3 i = lo4 for j in range(lo, hi):5 if a[j] < p:6 a[i], a[j] = a[j], a[i]7 i += 18 a[i], a[hi] = a[hi], a[i]9 return i10 11a = [3, 8, 2, 5, 1, 4]12k = partition(a, 0, 5)13print(a, k)
Using this step's partition (the last number is the pivot), what does 3 8 1 9 2 6 look like after one partition?
[1 2 3 6 8 9].Write Lomuto partitioning
✓Complete partition(a, lo, hi): with a[hi] as the pivot, swap the items of a[lo..hi] smaller than it to the left, put the pivot in its final place, and return that index.
3 [4, 2, 1, 5, 7, 6] 2 [1, 2, 3, 9, 7, 8] 2 [5, 1, 2, 6]
1def partition(a, lo, hi):2 p = a[hi]3 i = lo4 # j scans from lo to hi - 1: if a[j] < p, swap it with a[i] and move i right5 # finally swap the pivot with a[i]6 return i7 8a = [4, 7, 2, 6, 1, 5]9print(partition(a, 0, 5), a)10b = [9, 1, 8, 2, 7, 3]11print(partition(b, 0, 5), b)12c = [5, 6, 1, 2]13print(partition(c, 1, 3), c)
Recursion: partition each side again
One partition is O(n): j scans once and each item is compared with the pivot once. Where the pivot lands is its final place, and it never moves again; then each side is partitioned in turn:
1def partition(a, lo, hi):2 p = a[hi]3 i = lo4 for j in range(lo, hi):5 if a[j] < p:6 a[i], a[j] = a[j], a[i]7 i += 18 a[i], a[hi] = a[hi], a[i]9 return i10 11def quick_sort(a, lo, hi):12 if lo >= hi:13 return14 k = partition(a, lo, hi)15 quick_sort(a, lo, k - 1)16 quick_sort(a, k + 1, hi)17 18a = [4, 7, 2, 6, 1, 5]19print(partition(a, 0, 5), a)20 21b = [4, 7, 2, 6, 1, 5, 3, 3]22quick_sort(b, 0, len(b) - 1)23print(b)
3 [4, 2, 1, 5, 7, 6] [1, 2, 3, 3, 4, 5, 6, 7]
Once the pivot lands at index k, where is the left stretch? Fill in the blank so the program sorts.
1def partition(a, lo, hi):2 p = a[hi]3 i = lo4 for j in range(lo, hi):5 if a[j] < p:6 a[i], a[j] = a[j], a[i]7 i += 18 a[i], a[hi] = a[hi], a[i]9 return i10 11def quick_sort(a, lo, hi):12 if lo >= hi:13 return14 k = partition(a, lo, hi)15 quick_sort(a, lo, )16 quick_sort(a, k + 1, hi)17 18b = [4, 7, 2, 6, 1, 5, 3, 3]19quick_sort(b, 0, len(b) - 1)20print(b)
k or hi, some stretch never gets shorter and the recursion never stops (RecursionError); with lo, the left stretch is never sorted at all.After one partition, how many numbers are known to be in their final place?
Sorted input: degenerating to O(n²)
Quicksort is fast because each partition roughly halves a stretch, giving log n levels of O(n) each. But if the pivot is the first item (or the last) and the input is already sorted, the pivot is always the smallest: one side is empty and the other holds all the rest.
Let's count. For the first item as pivot, swap it to the end first and use the same partition. The other choice is median-of-three: look at the stretch's first, middle and last items and use the middle-sized one of the three as pivot. On sorted input, the middle one is exactly the median.
1stats = {"cmps": 0, "depth": 0}2 3def partition(a, lo, hi):4 p = a[hi]5 i = lo6 for j in range(lo, hi):7 stats["cmps"] += 18 if a[j] < p:9 a[i], a[j] = a[j], a[i]10 i += 111 a[i], a[hi] = a[hi], a[i]12 return i13 14def pick_first(a, lo, hi):15 return lo16 17def pick_median3(a, lo, hi):18 mid = (lo + hi) // 219 trio = sorted([(a[lo], lo), (a[mid], mid), (a[hi], hi)])20 return trio[1][1] # the index of the middle-sized one21 22def quick_sort(a, lo, hi, pick, depth=1):23 if lo >= hi:24 return25 stats["depth"] = max(stats["depth"], depth)26 m = pick(a, lo, hi)27 a[m], a[hi] = a[hi], a[m] # move the chosen pivot to the end28 k = partition(a, lo, hi)29 quick_sort(a, lo, k - 1, pick, depth + 1)30 quick_sort(a, k + 1, hi, pick, depth + 1)31 32n = 12033for pname, pick in [("first", pick_first), ("median-of-three", pick_median3)]:34 for name, data in [("sorted", list(range(n))), ("reversed", list(range(n, 0, -1))), ("mixed", [(i * 7919) % 10007 for i in range(n)])]:35 stats["cmps"] = stats["depth"] = 036 quick_sort(data, 0, n - 1, pick)37 print(pname, name, "comparisons", stats["cmps"], "depth", stats["depth"])
first sorted comparisons 7140 depth 119 first reversed comparisons 7140 depth 119 first mixed comparisons 893 depth 12 median-of-three sorted comparisons 600 depth 6 median-of-three reversed comparisons 882 depth 12 median-of-three mixed comparisons 721 depth 9
With the first item as pivot, mixed input takes only 893 comparisons and 12 levels; sorted and reversed both take 7140 = 120 × 119 / 2, 119 levels deep. Median-of-three brings sorted input down to 600 comparisons and 6 levels.
Only 120 numbers are used here because in Python degenerating costs more than time: the recursion depth equals n. 2000 sorted numbers with the first item as pivot go 2000 levels deep, past Python's default recursion limit of 1000, and fail with RecursionError.
The first item as pivot, sorting 6 numbers that are already sorted. What comparison count and recursion depth does it print?
1cmps = 02depth = 03 4def partition(a, lo, hi):5 global cmps6 p = a[hi]7 i = lo8 for j in range(lo, hi):9 cmps += 110 if a[j] < p:11 a[i], a[j] = a[j], a[i]12 i += 113 a[i], a[hi] = a[hi], a[i]14 return i15 16def quick_sort(a, lo, hi, d=1):17 global depth18 if lo >= hi:19 return20 depth = max(depth, d)21 a[lo], a[hi] = a[hi], a[lo] # first item as pivot: move it to the end22 k = partition(a, lo, hi)23 quick_sort(a, lo, k - 1, d + 1)24 quick_sort(a, k + 1, hi, d + 1)25 26a = [1, 2, 3, 4, 5, 6]27quick_sort(a, 0, 5)28print(cmps, depth)
With the first number as pivot (moved to the end, then a Lomuto partition), which inputs make quicksort degrade to O(n²)? (You can pick more than one.)
a[j] < p is never true, the pivot lands at the far left and n − 1 are left on the right, just as slow. With shuffled input, the pivot mostly lands somewhere near the middle.Fixing it: a better way to pick the pivot
With the first item as pivot, sorted and reversed input both degrade to O(n²), and the recursion goes n levels deep. The partition isn't the problem; a lopsided pivot is.
Two fixes:
- Median-of-three (
pick_median3from the previous stage): the result is fixed, and sorted and reversed input both do well. Many C libraries do this. - A random pivot:
m = random.randint(lo, hi). No input is always bad, and the expected cost is O(n log n); only the number of comparisons differs from run to run (the sorted result is of course the same).
You can also keep the recursion depth within log₂ n: recurse only into the shorter stretch, and keep partitioning the longer one in a loop.
1import random2 3def partition(a, lo, hi):4 p = a[hi]5 i = lo6 for j in range(lo, hi):7 if a[j] < p:8 a[i], a[j] = a[j], a[i]9 i += 110 a[i], a[hi] = a[hi], a[i]11 return i12 13def quick_sort(a, lo, hi):14 while lo < hi:15 m = random.randint(lo, hi) # a random pivot16 a[m], a[hi] = a[hi], a[m]17 k = partition(a, lo, hi)18 if k - lo < hi - k: # recurse into the shorter stretch, loop on the longer19 quick_sort(a, lo, k - 1)20 lo = k + 121 else:22 quick_sort(a, k + 1, hi)23 hi = k - 124 25data = list(range(3000))26quick_sort(data, 0, len(data) - 1)27print(data == list(range(3000)))28mixed = [(i * 7919) % 10007 for i in range(1000)]29quick_sort(mixed, 0, len(mixed) - 1)30print(mixed == sorted(mixed), mixed[:5])
True True [0, 9, 19, 28, 38]
Even 3000 sorted numbers are fine: the stretch it recurses into is less than half each time, so the depth is at most log₂ 3000 ≈ 12.
| Three-line version | In place, first item as pivot | In place, median-of-three / random | |
|---|---|---|---|
| Readability | easiest | you need partition | a few more lines |
| Extra space | new lists at every level, O(n) or more | recursion stack, worst O(n) | recursion stack O(log n) |
| Mixed input | O(n log n), twice the comparisons | O(n log n) | O(n log n) |
| Sorted input | O(n²), n levels of recursion | O(n²), n levels of recursion | O(n log n) |
| Stable | stable (comprehensions keep order) | not stable | not stable |
In interviews: asked for "quicksort's worst case": the pivot is the largest or smallest every time, O(n²); sorted input with the first item as pivot does exactly that; the fix is a random pivot or median-of-three. On space: the recursion stack is O(log n) on average and O(n) at worst, and recursing into the shorter stretch first guarantees O(log n). One more common trap: input where everything is equal is O(n²) for Lomuto too, since nothing is "smaller than" the pivot; the answer is three-way partitioning (smaller, equal, larger).
"Median of three" looks at a[lo], a[mid] and a[hi] and takes the middle one as the pivot. For the sorted 1 2 3 4 5 6 7, which pivot does it pick?
A random pivot, plus "recurse only into the shorter stretch, loop on the longer one": about how deep does the recursion go for n numbers?
Median-of-three
✓partition and quick_sort are written. Complete median3(a, lo, hi): of a[lo], a[mid] and a[hi] (mid = (lo + hi) // 2), find the middle-sized one and return its index. The recursion depth for 100 sorted numbers drops from 99 to 6.
1 2 0 True 6
1depth = 02 3def partition(a, lo, hi):4 p = a[hi]5 i = lo6 for j in range(lo, hi):7 if a[j] < p:8 a[i], a[j] = a[j], a[i]9 i += 110 a[i], a[hi] = a[hi], a[i]11 return i12 13def median3(a, lo, hi):14 mid = (lo + hi) // 215 # return whichever of lo, mid, hi holds the middle-sized value16 return hi17 18def quick_sort(a, lo, hi, d=1):19 global depth20 if lo >= hi:21 return22 depth = max(depth, d)23 m = median3(a, lo, hi)24 a[m], a[hi] = a[hi], a[m]25 k = partition(a, lo, hi)26 quick_sort(a, lo, k - 1, d + 1)27 quick_sort(a, k + 1, hi, d + 1)28 29print(median3([1, 5, 9], 0, 2), median3([9, 1, 5], 0, 2), median3([5, 9, 1], 0, 2))30data = list(range(100))31quick_sort(data, 0, 99)32print(data == list(range(100)), depth)
How you write it at work
Python has no built-in quicksort: sorted and list.sort are Timsort, stable and O(n log n) even at worst, so bad input is no worry. You write quicksort yourself only for interviews and for learning algorithms.
What is really used from quicksort is the idea of partitioning: splitting data into two piles by a condition. At work two comprehensions do it, clearly and in O(n):
1orders = [120, 35, 980, 60, 450, 15]2small = [x for x in orders if x < 100]3large = [x for x in orders if x >= 100]4print(small, large)5 6# when you just need the piles, sorted with a key works too: False sorts before True7print(sorted(orders, key=lambda x: x >= 100))
[35, 60, 15] [120, 980, 450] [35, 60, 15, 120, 980, 450]
key=lambda x: x >= 100 puts those under 100 (False) first, and because the sort is stable, each pile keeps its original order.
- Sorting:
sorted/list.sort; don't write your own quicksort. - Splitting into two piles by a condition: two comprehensions, or
sorted(..., key=condition). - The k-th smallest without sorting everything: quickselect (partition only one side, O(n) on average), in this chapter's last lesson.
Sorted by "is it 100 or more". What does it print?
1print(sorted([5, 120, 3, 300, 50], key=lambda x: x >= 100))Summary
Quicksort
- Pick a pivot, smaller items left and larger right, then sort each side; where the pivot lands is final
- The three-line comprehension version reads best but is not in place, makes new lists at every level and scans twice
- Lomuto: p = a[hi], j scans, items smaller than p swap into a[i], finally the pivot swaps into a[i]
- First item as pivot + sorted input = O(n²) and n levels of recursion; median-of-three or a random pivot fixes it
- O(n log n) on average, in place, not stable; at work use sorted
1def quick_sort(a, lo, hi):2 if lo >= hi:3 return4 k = partition(a, lo, hi)5 quick_sort(a, lo, k - 1)6 quick_sort(a, k + 1, hi)