Quicksort
Pick a pivot, split the rest into smaller and larger values, and sort both parts recursively. Fast on average. The in-place version needs almost no extra memory.
SolvesSorting
- best
- O(n log n)
- average
- O(n log n)
- worst
- O(n^2)
- space
- O(log n)
Quicksort picks a pivot, moves smaller values before it and larger values after it, and sorts both sides the same way [1].
Every pivot is the median of its segment, so each split is even. That gives log₂ n levels of n comparisons: O(n log n). Here: 10 comparisons.
pivot = —
1def quicksort(a):2 if len(a) <= 1:3 return a4 pivot = a[-1]5 # two new lists: extra memory on every call6 smaller = []7 larger = []8 for x in a[:-1]:9 if x < pivot:10 smaller.append(x)11 else:12 larger.append(x)13 left = quicksort(smaller)14 right = quicksort(larger)15 return left + [pivot] + right1 / 33
len(a) = 7: split it.
- comparisons
- 0
- copies
- 0
How it works
- If the list has at most one element, it is sorted.
- Take the last element as
pivot. - Partition: compare every other element with
pivot. Smaller ones go left, the rest go right. The pivot now sits at its final position. - Sort the left and right parts recursively.
Complexity
| Case | Input | Comparisons | Time |
|---|---|---|---|
| Best | pivot = median | ||
| Average | random | ||
| Worst | sorted (last = max) |
Each level of recursion compares elements. Even splits give levels. The worst splits give levels [2].
Implementations
Both use the same pivot rule, so they split the same way on best and worst inputs.
- Simple builds two new lists per call and joins them. Every level copies all values: extra memory per level.
- In-place (Lomuto partition) keeps
a[low..i-1] < pivotand swaps each smaller value to indexi. It copies nothing. The only extra memory is the recursion stack, on average.
Pitfalls
- A fixed pivot (first or last element) makes sorted input the worst case. Real implementations pick a random pivot or the median of three.
- All keys equal is also a worst case. Every value goes to the right part, so the splits are as uneven as on sorted input. A three-way partition fixes this.
- Quicksort is not stable: equal values can change order.
Related
Insertion Sort
Build a sorted prefix one element at a time by sliding each new key left into place. Simple, stable, in-place and fast on nearly sorted data.
Introsort
Quicksort that watches its recursion depth. Too deep, it switches to heap sort. Small parts go to insertion sort. Fast on average, O(n log n) always.
References
- C. A. R. Hoare, “Quicksort,” The Computer Journal, vol. 5, no. 1, pp. 10–16, 1962. doi.org/10.1093/comjnl/5.1.10
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.
Further reading
- D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.