Quick sort
medium 18 minQuick sort picks a pivot, partitions the array so smaller values sit to its left and larger values to its right, and then sorts each side the same way.
Video lesson · Chapter 1 of 6
The pivot book
Quicksort — Zia’s pivot crate
1:42Reel
Read caption
Porter Zia partitions five cargo crates around weight 4, placing it permanently before sorting the two smaller ranges. Partition once. Sort each side.
How it works
Step through the idea, or press Play.
Choose a pivot. Pick one value as the reference: the last, the middle, a random one or the median of three
Understand it
Start here
What quick sort is
Quick sort is a divide-and-conquer sorting algorithm. Think of a class lining up by height: pick one student as the reference (the pivot), have everyone shorter stand on their left and everyone taller on their right, then repeat inside each group. The reference student is already standing exactly where they belong.
Choose pivot
Select one value as the reference. Commonly the last, the first, the middle or a random value.
Partition
Rearrange in place: smaller values to the left of the pivot, larger values to the right.
Recurse
Apply the same process to the left part and the right part until every part has at most one value.
- 1PickChoose a pivot
- 2PartitionSmaller left, larger right
- 3SortThe left part, recursively
- 4RecurseOn the right part too
Pick, Partition, Sort left, Recurse right. The pivot is placed during Partition, so there is nothing to combine at the end.
The algorithm
Divide, conquer, nothing to combine
quick_sort(arr, low, high)
partition, before the recursive calls. Merge sort is the mirror image: it splits for free and does its work while merging on the way back up.def quick_sort(arr, low=0, high=None): if high is None: high = len(arr) - 1 if low < high: p = partition(arr, low, high) # pivot is final at p quick_sort(arr, low, p - 1) # left of the pivot quick_sort(arr, p + 1, high) # right of the pivot return arrdef partition(arr, low, high): pivot = arr[high] # last value is the pivot i = low - 1 # end of the "< pivot" zone for j in range(low, high): if arr[j] < pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1print(quick_sort([8, 3, 7, 4, 9, 2, 6, 5]))# [2, 3, 4, 5, 6, 7, 8, 9]Partitioning
The Lomuto scheme
Lomuto's partition uses the last value as the pivot and two indexes: j scans every other value from left to right, and i marks the end of the zone of values smaller than the pivot. Whenever j finds a smaller value, the zone grows by one and that value is swapped into it. At the end the pivot is swapped into the slot just after the zone, i + 1.
Lomuto partition loop
Loop invariant of Lomuto
| j | arr[j] | ? | Action | Array after |
|---|---|---|---|---|
| 0 | 8 | no | skip | 8, 3, 7, 4, 9, 2, 6, 5 |
| 1 | 3 | yes | i = 0, swap 0 and 1 | 3, 8, 7, 4, 9, 2, 6, 5 |
| 2 | 7 | no | skip | 3, 8, 7, 4, 9, 2, 6, 5 |
| 3 | 4 | yes | i = 1, swap 1 and 3 | 3, 4, 7, 8, 9, 2, 6, 5 |
| 4 | 9 | no | skip | 3, 4, 7, 8, 9, 2, 6, 5 |
| 5 | 2 | yes | i = 2, swap 2 and 5 | 3, 4, 2, 8, 9, 7, 6, 5 |
| 6 | 6 | no | skip | 3, 4, 2, 8, 9, 7, 6, 5 |
| end | swap pivot into i + 1 = 3 | 3, 4, 2, 5, 9, 7, 6, 8 |
Worked example
Sorting [8, 3, 7, 4, 9, 2, 6, 5]
| Call (low, high) | Subarray | Pivot | After partition | Pivot lands at |
|---|---|---|---|---|
| (0, 7) | 8, 3, 7, 4, 9, 2, 6, 5 | 5 | 3, 4, 2, 5, 9, 7, 6, 8 | 3 |
| (0, 2) | 3, 4, 2 | 2 | 2, 4, 3 | 0 |
| (1, 2) | 4, 3 | 3 | 3, 4 | 1 |
| (4, 7) | 9, 7, 6, 8 | 8 | 7, 6, 8, 9 | 6 |
| (4, 5) | 7, 6 | 6 | 6, 7 | 4 |
The recursion tree
Partitioning
The Hoare scheme
Tony Hoare's original 1961 partition walks two pointers towards each other. i moves right until it finds a value pivot, j moves left until it finds a value pivot, and the pair is swapped because both are on the wrong side. When the pointers cross, j is the split point: every value in [low..j] is pivot and every value in [j+1..high] is pivot.
Hoare partition loop
def hoare_partition(arr, low, high): pivot = arr[(low + high) // 2] i, j = low - 1, high + 1 while True: i += 1 while arr[i] < pivot: i += 1 j -= 1 while arr[j] > pivot: j -= 1 if i >= j: return j arr[i], arr[j] = arr[j], arr[i]def quick_sort_hoare(arr, low=0, high=None): if high is None: high = len(arr) - 1 if low < high: p = hoare_partition(arr, low, high) quick_sort_hoare(arr, low, p) quick_sort_hoare(arr, p + 1, high) return arrprint(quick_sort_hoare([8, 3, 7, 4, 9, 2, 6, 5])) # [2, 3, 4, 5, 6, 7, 8, 9]print(quick_sort_hoare([5, 5, 5, 5, 5, 5])) # equal values split evenly| Lomuto | Hoare | |
|---|---|---|
| Pointers | both move right ( trails ) | move towards each other |
| Pivot | last value | usually the middle value |
| Pivot after partition | in its final slot at | somewhere in the range, not fixed |
| Recursive calls | (low, p - 1) and (p + 1, high) | (low, p) and (p + 1, high) |
| Swaps on random data | about | about , three times fewer |
| All values equal | split: | even split: |
| Ease of writing | simpler, popular in teaching | trickier boundaries |
Complexity
Best case: O(n log n)
The best case is when every pivot is the median of its range, so each partition splits values into two halves. Partitioning a range of values costs comparisons, and then two problems of half the size remain.
Best-case recurrence
Unrolling it level by level
| n | levels | best case about | worst case |
|---|---|---|---|
| 8 | 3 | 24 | 28 |
| 64 | 6 | 384 | 2,016 |
| 1,024 | 10 | 10,240 | 523,776 |
| 1,000,000 | about 20 | about 20 million | about 500 billion |
Complexity
Worst case: O(n²)
The worst case is when every pivot is the smallest or largest value of its range. The partition then peels off just the pivot and leaves values on one side. With a last-value pivot this happens on sorted, reversed and nearly sorted input, the inputs people most often feed in.
Worst-case recurrence
Balanced versus lopsided splits
Complexity
Average case: still O(n log n)
Why is the average close to the best case and not the worst? Because a split does not need to be perfect, only not terrible. Even a fixed 1 : 9 split every time keeps the depth logarithmic.
A lopsided but constant split is fine
Expected comparisons with a random pivot
Solving the recurrence
Memory and order
O(log n) space, and not stable
Stack space
def quick_sort(arr, low=0, high=None): if high is None: high = len(arr) - 1 while low < high: p = partition(arr, low, high) if p - low < high - p: quick_sort(arr, low, p - 1) # smaller side: recurse low = p + 1 # larger side: loop else: quick_sort(arr, p + 1, high) high = p - 1 return arrdef partition(arr, low, high): pivot, i = arr[high], low - 1 for j in range(low, high): if arr[j] < pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1print(quick_sort(list(range(3000))) == list(range(3000))) # True, no RecursionErrorPivot choice
Choosing a good pivot
Last (or first) value
Simplest to code, fine for teaching. Degrades to on sorted and reversed input.
Random value
Swap a random value to the end first. No input is bad on purpose: expected for every input. A good default in production.
Median of three
Take the median of the first, middle and last values. Cheap, and it turns sorted input into the best case.
Middle value
Simple and works well on nearly sorted data, but crafted inputs can still defeat it.
Which pivot strategy?
std::sort) watches the recursion depth and falls back to heap sort past about levels, which caps the worst case at .| Input (n = 7) | Last-value pivot | Median of three |
|---|---|---|
| Random [8, 3, 7, ...] style | about | about |
| Sorted [1, 2, 3, 4, 5, 6, 7] | 21 comparisons | 10 comparisons |
| Reversed [7, 6, 5, 4, 3, 2, 1] | 21 comparisons | 10 comparisons |
| Nearly sorted [1, 2, 4, 3, 5, 6, 7] | 19 comparisons | 11 comparisons |
Head to head
Quick sort vs merge sort vs heap sort
| Property | Quick sort | Merge sort | Heap sort |
|---|---|---|---|
| Best time | |||
| Average time | , about comparisons | ||
| Worst time | |||
| Extra space | stack | buffer | |
| Stable | No | Yes | No |
| In place | Yes | No (for arrays) | Yes |
| Cache behaviour | Excellent: sequential scans | Good | Poor: jumps around the heap |
| Pivot matters | Critical | Not applicable | Not applicable |
Good for
- Arrays, where random access makes swaps cheap.
- Large in-memory datasets with a good pivot rule.
- When average is acceptable and speed matters.
- Memory-constrained code: it sorts in place.
- General-purpose sorting of numbers, and selection problems via quickselect.
Avoid when
- Data may be sorted and the pivot is naive: use a random pivot, or insertion sort for nearly sorted data.
- A guaranteed worst case is required: use merge sort or heap sort.
- Stability is required: quick sort is not stable.
- Sorting a linked list: no random access, so merge sort is the natural fit.
- Tiny arrays: insertion sort has less overhead below a few dozen values.
Recap
Key takeaways
Key points
- Quick sort picks a pivot, partitions smaller values left and larger values right, and recurses on both sides; the pivot ends in its final slot.
- Lomuto: last-value pivot, comparisons per partition, recurse on and . Hoare: two inward pointers, fewer swaps, recurse on and .
- Best case ; worst case ; average about .
- The worst case comes from always picking the min or max, as a last-value pivot does on sorted input. Random or median-of-three pivots fix it.
- In place with stack on average ( worst, with smaller side first). Not stable.
- Real libraries combine it: introsort switches to heap sort when recursion gets deep and to insertion sort for small ranges.