Quicksort
How quicksort partitions an array around a pivot, why the choice of pivot decides its speed, and what interviewers ask about it.
On this page
- How quicksort works
- Partitioning, step by step
- Code
- Running time and memory
- Choosing the pivot
- Lomuto and Hoare partitioning
- Arrays with many equal items
- Finding the k-th smallest item with quickselect
- Stability and memory
- Where quicksort is used
- Pitfalls when implementing quicksort
- In the interview
- What to practise next
Quicksort is a sorting algorithm that picks one item, called the pivot, and rearranges the array so that smaller items come before the pivot and the other items come after it. It then sorts the two parts the same way. It sorts in place, needs very little extra memory, and is fast in practice, which is why it is the basis of the default sort in many standard libraries. You reach for it when you need to sort an array in memory and do not need equal items to keep their original order.
How quicksort works
Quicksort repeats three steps on a range of the array. First, it picks a pivot from the range. Second, it partitions the range, which means moving the items smaller than the pivot before it and the remaining items after it, so that the pivot ends up in its final sorted position. Third, it calls itself on the part before the pivot and on the part after it. A range with zero or one item is already sorted, so the recursion stops there.
Merge sort also splits the array, but it splits blindly in the middle and does its real work when it merges the sorted halves. Quicksort does its work while splitting, so there is nothing to combine afterwards: once both sides are sorted, the whole range is sorted.
Partitioning, step by step
The version below uses the last item as the pivot. A boundary index b marks where the next smaller item should go, so everything before b is smaller than the pivot. A second index j scans the range once from left to right. When a[j] is smaller than the pivot, it is swapped into slot b and b moves right. After the scan, the pivot is swapped into slot b, which is its final position.
pivot = a[hi]b = lofor j from lo to hi - 1: if a[j] < pivot: swap a[b] and a[j] b = b + 1swap a[b] and a[hi]return b- a07b j1229344156
- pivot
- 6
- comparisons
- 0
1The pivot is the last item, 6, and
bstarts at the front of the range. - a07b j1229344156
- pivot
- 6
- comparisons
- 1
27 is not smaller than 6, so it stays where it is and only
jmoves. - a0217b j29344156
- pivot
- 6
- comparisons
- 2
32 is smaller than 6, so it is swapped into slot
b, which sends 7 to slot 1, and thenbmoves right. - a0217b29j344156
- pivot
- 6
- comparisons
- 3
49 is not smaller than 6, so it stays and only
jmoves. - a021429b37j4156
- pivot
- 6
- comparisons
- 4
54 is smaller than 6, so it is swapped with the 7 in slot
b, and thenbmoves right. - a02142137b49j56
- pivot
- 6
- comparisons
- 5
61 is smaller than 6, so it is swapped with the 9 in slot
b. The items 2, 4 and 1 are now packed at the front. - a02142136b4957
- pivot
- 6
- comparisons
- 5
7The scan is finished, so the pivot is swapped into slot
b. Everything before it is smaller and everything after it is larger, so 6 is in its final place. - a021421364957
- returns
- 3
8Partition returns 3. Quicksort now calls itself on
[2, 4, 1]and on[9, 7], and the two parts never need to be compared with each other again. - a011224364759
9After both parts are sorted, the whole array is sorted. A single pass of 5 comparisons fixed the pivot and split the problem in two.
Code
This is the partition from the trace with one addition: it first swaps a randomly chosen item to the end, so the pivot is random. The section on pivot choice explains why.
function quickSort(a, lo = 0, hi = a.length - 1) {
if (lo >= hi) return a; // 0 or 1 items: sorted
const p = partition(a, lo, hi);
quickSort(a, lo, p - 1); // the pivot at p is already final
quickSort(a, p + 1, hi);
return a;
}
function partition(a, lo, hi) {
const r = lo + Math.floor(Math.random() * (hi - lo + 1));
[a[r], a[hi]] = [a[hi], a[r]]; // random pivot, moved to the end
const pivot = a[hi];
let b = lo; // a[lo..b-1] holds items smaller than the pivot
for (let j = lo; j < hi; j++) {
if (a[j] < pivot) {
[a[b], a[j]] = [a[j], a[b]];
b++;
}
}
[a[b], a[hi]] = [a[hi], a[b]]; // pivot into its final slot
return b;
}
quickSort([7, 2, 9, 4, 1, 6]); // [1, 2, 4, 6, 7, 9]import random
def quick_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi: # 0 or 1 items: sorted
return a
p = partition(a, lo, hi)
quick_sort(a, lo, p - 1) # the pivot at p is already final
quick_sort(a, p + 1, hi)
return a
def partition(a, lo, hi):
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r] # random pivot, moved to the end
pivot = a[hi]
b = lo # a[lo..b-1] holds items smaller than the pivot
for j in range(lo, hi):
if a[j] < pivot:
a[b], a[j] = a[j], a[b]
b += 1
a[b], a[hi] = a[hi], a[b] # pivot into its final slot
return b
quick_sort([7, 2, 9, 4, 1, 6]) # [1, 2, 4, 6, 7, 9]Running time and memory
Partitioning a range of n items costs O(n), because it is one scan. The total cost therefore depends on how many levels of recursion there are, and that depends on how evenly each pivot splits its range.
| Approach | Time | Space | Why |
|---|---|---|---|
| Average (random pivot) | O(n log n) | O(log n) | About log n levels of O(n) partitioning. The space is the recursion stack. |
| Worst case | O(n²) | O(n) | Every pivot is the smallest or largest item, so each level removes only one item. |
If pivots land near the middle, each level halves the ranges, as in merge sort, so there are about log n levels of O(n) work. If the pivot is always the smallest or largest item of its range, one side is empty and the other side holds everything else, so each level removes only the pivot. The work is then n + (n − 1) + … + 1, which is O(n²), and the recursion is n calls deep.
Choosing the pivot
First or last item
Taking the first or last item is the simplest choice, and it is what the trace above does. It is also the one that fails on realistic input. If the array is already sorted or sorted in reverse, which happens often with timestamps, IDs and log files, every pivot is the smallest or largest item of its range and the sort takes O(n²) time.
Random pivot
Choosing the pivot at random removes the dependence on the input order. No particular input can force bad splits, because the choice is made fresh on every run. The expected running time is O(n log n) for any input of distinct items,. This is the version in the code above,.
Median of three
Taking the median of the first, middle and last items handles sorted and reversed input without random numbers, and many libraries use it. A carefully built input can still force bad splits, which is why libraries add a fallback, described below.
Lomuto and Hoare partitioning
The partition used so far is called the Lomuto scheme: one index scans the range, and a boundary index tracks where the next smaller item goes. The older Hoare scheme uses two indexes that start at the two ends of the range and move toward each other. The left index moves right until it finds an item that is not smaller than the pivot, the right index moves left until it finds an item that is not larger than the pivot, and if the indexes have not crossed yet, the two items are swapped. It makes far fewer swaps than Lomuto on random input.
Hoare's scheme also stops both indexes on items equal to the pivot, so an array of identical items is split in the middle and stays O(n log n) without a three-way partition. The cost is that it does not place the pivot in its final slot. It returns a split point, the recursion covers [lo, p] and [p + 1, hi], and the loop bounds are easy to get wrong. In an interview, Lomuto is easier to write correctly, and Hoare is worth mentioning when you are asked how to make partitioning faster or how to handle equal items.
Arrays with many equal items
The partition above puts items equal to the pivot on the right side, because only strictly smaller items are moved left. If every item is the same, the condition a[j] < pivot is never true, so the pivot ends up in the first slot of the range and the right side holds everything else. Every level then removes one item, and the sort takes O(n²) time even with a random pivot.
The fix is a three-way partition, which splits the range into items smaller than the pivot, items equal to the pivot and items larger than the pivot. It keeps three regions with two boundary indexes and one scanning index. A smaller item is swapped to the end of the left region, a larger item is swapped to the start of the right region, and an equal item is left in the middle. Quicksort then recurses only on the smaller and larger regions and never touches the equal ones again. With three-way partitioning, an array of identical items takes one pass.
Finding the k-th smallest item with quickselect
After a partition, the pivot is at its final index p. If p equals the position you are looking for, the pivot is the answer. If p is larger, the answer is in the left part, and if p is smaller, the answer is in the right part. You recurse into that one part only, and you ignore the other. This is called quickselect.
If every pivot cut the range in half, the scans would cost n + n/2 + n/4 + …, which is less than 2n. A random pivot is not that good every time, but on average it still removes a constant fraction of the range, so the expected time is O(n), which beats sorting the whole array in O(n log n). The worst case is still O(n²), and quickselect rearranges the array it is given. When you only need the k largest items and can read them one at a time, a heap of size k is the alternative that never changes the input and works on a stream.
Stability and memory
Quicksort is not stable, which means equal items may change their relative order. The swaps throw items over each other. For example, partitioning [2a, 2b, 1] around the last item 1 swaps the 1 with the first item, which gives [1, 2b, 2a], and the two 2s have changed places. If you need ties to keep their original order, for example when sorting records by one field after another, use a stable sort such as merge sort.
Quicksort uses no buffer, but the recursion uses stack space. With random pivots the stack is O(log n) deep on average. You can make the depth O(log n) in the worst case as well by recursing into the smaller part first and handling the larger part in a loop, because the smaller part is at most half the range. Without that change, an unlucky run can use O(n) stack.
Where quicksort is used
Library sorts usually combine algorithms. C++'s std::sort is typically an introsort: it runs quicksort, switches to insertion sort for very small ranges, and switches to heap sort if the recursion gets too deep. That keeps quicksort's speed in practice while guaranteeing O(n log n) in the worst case.
Pitfalls when implementing quicksort
In the interview
Quicksort is asked in two forms. Sometimes you are asked to implement it directly, and then the interviewer cares about correct partitioning and the base case. More often a problem needs only the partition step. Look for these signals in the problem statement:
- "Find the k-th largest (or smallest) element" without a requirement to sort everything. Quickselect gives average O(n), and a heap gives O(n log k).
- "Rearrange the array so that items satisfying a condition come first", for example moving zeros to the end or separating even and odd numbers. This is one partition pass.
- An array that holds only a few distinct values, such as 0, 1 and 2 (sort colors). This is a three-way partition, and it runs in one pass with O(1) extra space.
Questions to expect:
- "What is the worst case, and when does it happen?" It is O(n²), and it happens when every pivot is the smallest or largest item of its range. A fixed pivot position on sorted or reversed input does this, and so does the partition above on an array of equal items.
- "How do you avoid the worst case?" Choose the pivot at random, which makes the expected time O(n log n) for every input. Median of three also works on common inputs. Add a three-way partition if many items can be equal.
- "Quicksort or merge sort?" Quicksort sorts arrays in place, has a small constant factor and works well with the CPU cache, but its worst case is O(n²) and it is not stable. Merge sort guarantees O(n log n) and is stable, but needs O(n) extra space for arrays.
- "Is quicksort stable? Can you make it stable?" It is not stable. Making it stable needs extra memory, which removes the in-place advantage, so use merge sort instead.
- "How do you find the median or k-th item faster than sorting?" Use quickselect: partition, then continue in only the side that holds position k. The average time is O(n) and the worst case is O(n²).
You partition [3, 8, 1, 5] using the last item, 5, as the pivot, with the code from the trace. Where does 5 end up?
Quicksort with the last item as pivot receives [1, 2, 3, …, 1000]. Roughly how many comparisons does it make?
An array of 100,000 identical numbers is sorted with this lesson's code, which moves only strictly smaller items to the left of the pivot. What happens?
What to practise next
Partition [5, 9, 2, 7, 3] by hand around 3 and check that you get [2, 3, 5, 7, 9] with the pivot at index 1. Then read Heap Sort, which guarantees O(n log n) in place on any input, or Counting and Radix Sort for sorting without comparisons.