Quick Sort
Quick sort is one of the fastest general-purpose sorting algorithms in practice. It is a divide and conquer algorithm: pick one value as the pivot, rearrange the array so that smaller values come before the pivot and larger values after it (partitioning), then sort the two sides the same way, recursively.
After partitioning, the pivot is already in its final position. The two sides are independent problems, and an empty or one-value side is sorted by definition, which is the base case of the recursion.
Lomuto partitioning
There are several ways to partition. The Lomuto scheme is the easiest to follow:
- Take the last value of the range as the pivot.
- Keep an index
i= "where the next smaller value goes", starting at the left end. - Walk
jover the range. Whenevera[j] < pivot, swapa[j]into positioniand moveione step right. - Finally swap the pivot into position
i. Everything left ofiis smaller, everything right of it is not.
Implementation
def partition(arr, lo, hi):
pivot = arr[hi]
i = lo
for j in range(lo, hi):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[hi] = arr[hi], arr[i]
return i
def quick_sort(arr, lo=0, hi=None, depth=0):
if hi is None:
hi = len(arr) - 1
if lo < hi:
pivot = arr[hi]
p = partition(arr, lo, hi)
print(f"{' ' * depth}partition {lo}..{hi} around {pivot}: {arr} (pivot now at {p})")
quick_sort(arr, lo, p - 1, depth + 1)
quick_sort(arr, p + 1, hi, depth + 1)
return arr
print(quick_sort([33, 12, 46, 5, 27, 18]))partition 0..5 around 18: [12, 5, 18, 33, 27, 46] (pivot now at 2)
partition 0..1 around 5: [5, 12, 18, 33, 27, 46] (pivot now at 0)
partition 3..5 around 46: [5, 12, 18, 33, 27, 46] (pivot now at 5)
partition 3..4 around 27: [5, 12, 18, 27, 33, 46] (pivot now at 3)
[5, 12, 18, 27, 33, 46]
The indentation shows the recursion depth. Each printed line corresponds to a "Put pivot … at position …" frame in the animation. Single-value ranges are skipped by lo < hi; the animation marks them as "alone is in place".
The worst case: a bad pivot
Quick sort is fast when the pivot splits the range into two halves of similar size: about log₂ n levels of recursion, each doing O(n) work, so O(n log n) in total. If the pivot is always the smallest or largest value, one side is empty and the other has n - 1 values. That gives n levels and O(n²) comparisons. With "last value as pivot", already sorted input is exactly this bad case:
def quick_sort_count(arr, lo, hi, stats, depth=1):
if lo >= hi:
return
stats["depth"] = max(stats["depth"], depth)
pivot = arr[hi]
i = lo
for j in range(lo, hi):
stats["comparisons"] += 1
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[hi] = arr[hi], arr[i]
quick_sort_count(arr, lo, i - 1, stats, depth + 1)
quick_sort_count(arr, i + 1, hi, stats, depth + 1)
# a fixed shuffled order of 0..63 (multiply by 37 modulo 64)
shuffled = [(k * 37) % 64 for k in range(64)]
for name, data in [("shuffled", shuffled), ("sorted", list(range(64)))]:
stats = {"comparisons": 0, "depth": 0}
quick_sort_count(data, 0, len(data) - 1, stats)
print(f"{name:>8}: {stats['comparisons']:>4} comparisons, recursion depth {stats['depth']}")shuffled: 311 comparisons, recursion depth 11
sorted: 2016 comparisons, recursion depth 63
Common fixes:
- Median-of-three: use the median of the first, middle and last value as the pivot.
- Randomised pivot: pick a random index, so no fixed input is reliably bad.
- Introsort (used by C++
std::sort): switch to heap sort if the recursion gets too deep.
A readable (but not in-place) version
Python makes the idea of quick sort very short if you don't mind building new lists. This version uses O(n) extra memory but shows the divide-and-conquer structure clearly. It also uses the middle value as the pivot and groups the values equal to it, which handles duplicates well:
def quick_sort_simple(values):
if len(values) <= 1:
return values
pivot = values[len(values) // 2]
smaller = [v for v in values if v < pivot]
equal = [v for v in values if v == pivot]
larger = [v for v in values if v > pivot]
return quick_sort_simple(smaller) + equal + quick_sort_simple(larger)
print(quick_sort_simple([33, 12, 46, 5, 27, 18, 12, 46]))
print(quick_sort_simple(list(range(10, 0, -1))))[5, 12, 12, 18, 27, 33, 46, 46]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Properties
| Property | Quick sort (Lomuto, in place) |
|---|---|
| Time, average | O(n log n) |
| Time, worst | O(n²) (bad pivots, e.g. sorted input with a last-value pivot) |
| Extra memory | O(log n) for the recursion on average |
| Stable? | No: partition swaps jump over equal values |
Note: Quick sort is usually faster than merge sort in practice because it works in place and accesses memory sequentially, which caches love. Its weakness is the worst case, which good pivot selection makes very unlikely.
Test yourself
What is guaranteed after one partition step?
- The whole array is sorted
- The pivot is in its final sorted position
- The smallest value is at index 0
- Both halves have the same length
With the last value as pivot, which input makes quick sort take O(n²) time?
- A shuffled array
- An already sorted array
- An array with all different values
- An array of length 1
Is in-place quick sort stable?
- Yes
- No