Quick sort picks a pivot, partitions the array so that smaller elements come before it and larger ones after it, then recursively sorts the two sides. It sorts in place, scans memory sequentially and averages about 1.39 n log₂ n comparisons, which makes it the fastest general-purpose comparison sort in practice. Its weakness is an O(n²) worst case when pivots are consistently bad, which randomization, three-way partitioning and introsort are designed to defuse.
Think of it like
Lining up for a class photo
The photographer picks one student and says: everyone shorter, stand to the left; everyone taller, to the right. That student is now in exactly the right spot. Each group then repeats the trick with its own chosen student. If the photographer keeps picking the tallest person in the group, though, nobody moves to the right and the process crawls: that is quick sort's worst case.
How it works
- 1
Choose a pivot
Pick one element of
a[lo..hi], for example the last one, a random one, or the median of three samples. - 2
Partition
Rearrange the range so every element smaller than the pivot is to its left and every larger element is to its right. The pivot is now in its final position.
- 3
Recurse
Sort the left part and the right part independently. There is no combine step: once both sides are sorted, the whole range is sorted.
Partition schemes
Lomuto partition
Take pivot = a[hi] and keep a boundary i such that a[lo..i-1] holds the elements known to be smaller than the pivot. Scan j from lo to hi - 1; whenever a[j] < pivot, swap it to position i and advance i. Finally swap the pivot into a[i].
| j | a[j] | a[j] < 4? | Array after the step | i |
|---|---|---|---|---|
| 0 | 2 | yes: swap a[0] with a[0] | [2, 8, 7, 1, 3, 5, 6, 4] | 1 |
| 1 | 8 | no | [2, 8, 7, 1, 3, 5, 6, 4] | 1 |
| 2 | 7 | no | [2, 8, 7, 1, 3, 5, 6, 4] | 1 |
| 3 | 1 | yes: swap a[1] with a[3] | [2, 1, 7, 8, 3, 5, 6, 4] | 2 |
| 4 | 3 | yes: swap a[2] with a[4] | [2, 1, 3, 8, 7, 5, 6, 4] | 3 |
| 5 | 5 | no | [2, 1, 3, 8, 7, 5, 6, 4] | 3 |
| 6 | 6 | no | [2, 1, 3, 8, 7, 5, 6, 4] | 3 |
| end | swap pivot into a[3] | [2, 1, 3, 4, 7, 5, 6, 8] | 3 |
[2, 8, 7, 1, 3, 5, 6, 4] around pivot 4. The pivot ends at index 3 with smaller values to its left.Hoare partition
Tony Hoare's original scheme moves two indices toward each other: i from the left skips elements smaller than the pivot, j from the right skips elements larger than it, and when both stop the two elements are swapped. When the indices cross, j splits the range into a[lo..j] (all ≤ pivot) and a[j+1..hi] (all ≥ pivot).
Lomuto
- Simple to write and to prove correct
- Pivot ends in its final position, handy for quickselect
- About 3 times more swaps than Hoare on average
- Degrades to O(n²) when all keys are equal
Hoare
- Fewer swaps: only pairs that are both out of place
- Equal keys stop both scans, so duplicates split evenly
- Pivot is not necessarily in its final position: recurse on
[lo, j]and[j+1, hi] - Pivot must not be
a[hi](usea[lo]or the middle) or recursion may never shrink
p; Hoare returns a split point j, and the last step compares both schemes' results and swap counts.Choosing the pivot
| Strategy | How | Weakness |
|---|---|---|
| First or last element | a[lo] or a[hi] | O(n²) on already-sorted or reverse-sorted input, which is very common in practice |
| Middle element | a[(lo + hi) / 2] | Fine on sorted input, but adversarial inputs still exist |
| Random element | Uniform index in [lo, hi] | Expected O(n log n) on every input; needs a random number generator |
| Median of three | Median of first, middle and last | Cheap and great on sorted data; crafted "median-of-3 killer" inputs still force O(n²) |
| Ninther | Median of three medians of three | Better pivots for large arrays; used by many library sorts |
| Median of medians | Deterministic linear-time median | Guarantees O(n log n), but the constant factor is too high for everyday use |
The worst case and why it happens
If the pivot is always the smallest or largest element, one side of every partition is empty and the other has n − 1 elements. The partitions shrink by only one element per level, so there are n levels doing n, n − 1, n − 2, … comparisons.
Average-case intuition
Quick sort does not need perfect splits. Even if every partition were a lopsided 9-to-1 split, the larger side would shrink by a factor of 10/9 per level, giving a depth of log_(10/9) n ≈ 6.6 log₂ n. Each level still costs at most n, so the total is O(n log n), just with a bigger constant.
With a random pivot, half of all choices land in the middle 50% of the values and produce a split no worse than 3-to-1. Good pivots are therefore common, and bad ones cannot persist. Solving the exact recurrence gives the expected comparison count below.
Three-way partitioning for duplicates
Two-way partitioning wastes effort on repeated keys: with Lomuto, an array of identical values triggers the O(n²) worst case. Three-way partitioning (Dijkstra's Dutch national flag problem) splits the range into three regions: less than, equal to, and greater than the pivot. The equal block is already in its final place, so only the outer two regions are recursed on.
| Region | Invariant |
|---|---|
a[lo..lt-1] | < pivot |
a[lt..i-1] | = pivot |
a[i..gt] | not yet examined |
a[gt+1..hi] | > pivot |
def quick_sort_3way(a: list[int], lo: int = 0, hi: int | None = None) -> list[int]:
if hi is None:
hi = len(a) - 1
if lo >= hi:
return a
pivot = a[lo] # use a random pivot in production code
lt, i, gt = lo, lo, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1 # do not advance i: the swapped-in value is unexamined
else:
i += 1
quick_sort_3way(a, lo, lt - 1) # strictly smaller keys
quick_sort_3way(a, gt + 1, hi) # strictly larger keys
return alt, i and gt maintain the four regions from the table above, and note that i does not advance after a swap with gt.Bounding the stack: tail-call elimination
Quick sort makes two recursive calls, but the second one can be replaced by a loop. The trick is to recurse into the smaller side and loop on the larger side. The smaller side has at most half the elements, so every recursive call at least halves the problem and the stack depth is at most log₂ n, even when the running time degrades to O(n²).
def quick_sort(a: list[int], lo: int, hi: int) -> None:
while lo < hi:
p = partition(a, lo, hi) # pivot ends at index p (Lomuto)
if p - lo < hi - p:
quick_sort(a, lo, p - 1) # smaller side: recurse (at most n/2 elements)
lo = p + 1 # larger side: continue the loop
else:
quick_sort(a, p + 1, hi)
hi = p - 1Introsort: the production answer
Introsort (David Musser, 1997) keeps quick sort's average speed and removes its worst case. It runs quick sort with a median-of-three pivot while counting the recursion depth. If the depth exceeds about 2⌊log₂ n⌋, the pivots are clearly going badly, so it switches that subarray to Heap Sort, which is O(n log n) in the worst case. Tiny subarrays are finished with Insertion Sort.
- 1
Quick sort
The fast path for almost every input: median-of-three pivots, in-place partitioning.
- 2
Heap sort fallback
Triggered when recursion gets too deep. Caps the worst case at O(n log n) with O(1) extra space.
- 3
Insertion sort finish
Subarrays below about 16 elements are handled by insertion sort, which is fastest at that size.
| Library | Algorithm |
|---|---|
C++ std::sort (libstdc++, MSVC) | Introsort |
.NET Array.Sort | Introsort |
Go sort.Sort (since 1.19), Rust sort_unstable (for many releases) | pdqsort, a pattern-defeating quick sort descended from introsort |
Java Arrays.sort for primitives | Dual-pivot quick sort (two pivots, three partitions) |
| Python, Java objects | Not quick sort: Timsort, because they need stability |
Quickselect: the k-th smallest element
To find the k-th smallest element you do not need to sort everything. Partition once: if the pivot lands at index k you are done; otherwise only one side can contain index k, so recurse (or loop) into that side only. The expected work is a geometric series.
p, and everything on the side without k is discarded. Pick k with the slider and compare the comparison count with a full quick sort; try the Sorted input with pivot a[hi] to see the quadratic worst case. The implementation below uses Hoare partitioning instead, which narrows to [lo, j] or [j+1, hi] and stops when lo == hi.Sort, then index
- O(n log n) time
- Gives every order statistic at once
- Simplest code
Size-k heap
- O(n log k) time, O(k) space
- Works on streams
- See Heap Sort
Quickselect
- O(n) expected time, O(1) space
- Reorders the input
- C++
std::nth_element, NumPypartition
Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Best | O(n log n) | O(log n) | Every pivot splits the range evenly |
| Average | O(n log n) | O(log n) | About 1.39 n log₂ n comparisons with random pivots |
| Worst | O(n²) | O(log n) | Always-extreme pivots; stack is O(n) unless you recurse on the smaller side |
| Introsort | O(n log n) | O(log n) | Heap sort fallback caps the worst case |
| Quickselect (average) | O(n) | O(1) | Iterative; recurse into one side only |
| Quickselect (worst) | O(n²) | O(1) | O(n) worst case with median-of-medians pivots |
In-place and not stable. Not adaptive in its basic form.
Implementation
The scheme shown in the visualization, plus a random pivot so sorted input is no longer a worst case. Still quadratic when all keys are equal.
import random
def quick_sort(a: list[int], lo: int = 0, hi: int | None = None) -> list[int]:
if hi is None:
hi = len(a) - 1
if lo < hi:
p = lomuto_partition(a, lo, hi)
quick_sort(a, lo, p - 1)
quick_sort(a, p + 1, hi)
return a
def lomuto_partition(a: list[int], lo: int, hi: int) -> int:
r = random.randint(lo, hi) # random pivot defeats sorted input
a[r], a[hi] = a[hi], a[r]
pivot = a[hi]
i = lo # a[lo:i] holds values < pivot
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] # pivot lands in its final slot
return iKey takeaways
- Quick sort partitions around a pivot (which lands in its final place) and recurses on both sides; there is no combine step.
- Average O(n log n) with about 1.39 n log₂ n comparisons; worst case O(n²) when pivots are always extreme.
- Random or median-of-three pivots defuse sorted inputs; three-way partitioning makes duplicates cheap instead of catastrophic.
- Recursing into the smaller side and looping on the larger bounds the stack at O(log n) even in the worst case.
- Introsort (quick sort + heap sort fallback + insertion sort) is what
std::sortactually runs, and quickselect finds the k-th element in expected O(n).
Common pitfalls
- Always choosing the first or last element as pivot, which makes already-sorted input (a very common case) quadratic.
- Using Lomuto on data with many equal keys, which degrades to O(n²); use Hoare or three-way partitioning.
- Using Hoare partition with
a[hi]as the pivot, or recursing on[lo, p - 1]and[p + 1, hi]after it, which can loop forever or skip elements. - Recursing naively on both sides, which can overflow the stack on adversarial or sorted inputs.
- Expecting stability: partitioning swaps elements over long distances.
Interview tips
- Explain why the worst case happens and three fixes (random pivot, median-of-three, introsort) rather than just stating O(n²).
- For Kth Largest Element, present sort, heap and quickselect with complexities before coding quickselect.
- Sort Colors is three-way partitioning in disguise; name the Dutch national flag algorithm when you see it.
- Know which libraries use which sort: introsort in C++, dual-pivot quick sort for Java primitives, Timsort when stability is required.
Real-world applications
- Default unstable sort in C++, .NET, Go and Rust standard libraries (as introsort or pdqsort).
- Selection problems: medians, percentiles and top-k via quickselect (
std::nth_element, NumPypartition). - In-memory sorting where extra memory is scarce and average speed matters most.
- Partitioning steps reused on their own, such as splitting data around a threshold.
Practice problems
Test yourself
Quick sort always picks the last element as pivot. Which input triggers its O(n²) worst case?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.