Quicksort
Quicksort, invented by Tony Hoare around 1960, is one of the most important algorithms ever designed. It is the basis of the sorting routines of many programming languages and libraries, and it is usually the fastest general-purpose sorting algorithm in practice. It improves the idea of exchange: instead of exchanging adjacent elements, it exchanges elements that are far apart, removing many inversions at once.
Quicksort is also our first example of a recursive algorithm based on divide and conquer, a paradigm that you will study in depth later in the course.
- The idea of partitioning around a pivot, and why it leads to a recursive algorithm.
- The criteria for choosing the pivot, and the median-of-three strategy.
- How the partitioning strategy works, step by step, with a complete trace.
- Why Quicksort is in the best and average cases but in the worst case.
- Its practical weaknesses (recursion depth, repeated keys, small subarrays) and how professional implementations address them.
The Idea: Partitioning
Quicksort is based on partitioning. Choose an element of the vector, called the pivot, and rearrange the vector so that:
- all the elements smaller than the pivot are on its left;
- all the elements greater than the pivot are on its right;
- the pivot is between them.
After partitioning, the pivot is in its final position: it will not move again. And the two parts on each side can be sorted independently, because no element will ever need to cross from one side to the other. So we apply the same idea to each part, recursively, until the parts have one element (or none), which are trivially sorted.
The sequence of partitions forms a tree. If each pivot divides its part into two halves of similar size, the tree is balanced and has about levels. If the pivot is always at one end of its part (the smallest or the largest element), one of the parts is empty and the "tree" degenerates into a list of levels. This is the key to the efficiency of Quicksort, as we will see in the analysis: the choice of the pivot is crucial.
Choosing the Pivot
The ideal pivot is the median of the elements (the element that would be in the middle if they were sorted), because it divides the part into two halves of equal size. The options are:
| Criterion | Assessment |
|---|---|
| The median | The ideal solution, but it is very expensive to compute exactly. |
| The first element | "Cheap", but a bad choice: on data that is already sorted (very common in practice), it is always the smallest element, and every partition is completely unbalanced. |
| The last element | Same problem as the first one. |
| A random element | Statistically, it is not a bad choice: no particular input is consistently bad. It has the cost of generating random numbers. |
| The central element | Statistically not a bad choice, and it works very well on sorted or reverse-sorted data. |
| Median-of-three | A compromise: take three elements (the first, the last and the central one), and use their median as the pivot. It does not guarantee anything, but it is a good indicator of the real median at a very low cost. |
The course implementation uses the median-of-three. It sorts the three elements among themselves (so the smallest ends up at the left end and the largest at the right end) and returns the position of the central one, which holds their median:
private int medianOfThree(int[] elements, int left, int right) {
int center = left + (right - left) / 2;
if (elements[left] > elements[center]) Util.swap(elements, left, center);
if (elements[left] > elements[right]) Util.swap(elements, left, right);
if (elements[center] > elements[right]) Util.swap(elements, center, right);
return center; // elements[left] <= elements[center] <= elements[right]
}
A useful side effect: if the part has three elements or fewer, the median-of-three has already sorted it completely, and the recursion can stop there.
The Partitioning Strategy
Once the pivot is chosen, the partition is done in place with two indices that move towards each other:
- Hide the pivot: exchange it with the last element, so that it does not get in the way.
- Move
ifrom the left until it finds an element greater than the pivot (an element that should be on the right). - Move
jfrom the right until it finds an element smaller than the pivot (an element that should be on the left). - If
iandjhave not crossed, exchange those two elements: each one goes to its correct side. - Repeat steps 2 to 4 until
iandjcross. Thenimarks the first position of the right part: place the pivot there by exchanging it with the last element.
private void quickSortRecursive(int[] elements, int left, int right) {
if (left >= right) return; // 0 or 1 elements: sorted
int center = medianOfThree(elements, left, right);
if ((right - left) >= 3) { // with 3 elements or fewer, already sorted
int pivot = elements[center];
Util.swap(elements, center, right); // hide the pivot at the end
int i = left;
int j = right - 1;
do {
while (elements[i] <= pivot && i < right) i++; // first element > pivot
while (elements[j] >= pivot && j > left) j--; // first element < pivot
if (i < j) Util.swap(elements, i, j);
} while (i < j);
Util.swap(elements, i, right); // place the pivot in its final position
quickSortRecursive(elements, left, i - 1); // sort the left part
quickSortRecursive(elements, i + 1, right); // sort the right part
}
}
public void sort(int[] elements) {
quickSortRecursive(elements, 0, elements.length - 1);
}
Complete trace
Let us sort 4 5 6 1 3 2 7 8 (positions 0 to 7).
- 1. First partition
- 2. Left part
- 3. Right part
- 4. Recursive calls
| Action | Vector | Comment |
|---|---|---|
| Median-of-three of 4, 1, 8 (positions 0, 3, 7) | 1 5 6 4 3 2 7 8 | The three are sorted among themselves; the pivot is 4. |
| Hide the pivot at the end | 1 5 6 8 3 2 7 4 | The 8 goes to position 3. |
i stops at 5 (greater than 4), j stops at 2 (smaller than 4): swap | 1 2 6 8 3 5 7 4 | |
i stops at 6, j stops at 3: swap | 1 2 3 8 6 5 7 4 | |
i stops at 8 (position 3), j stops at 3 (position 2): they cross | 1 2 3 8 6 5 7 4 | No swap. |
Place the pivot at position i = 3 | 1 2 3 4 6 5 7 8 | The 4 is in its final position. |
The left part is 1 2 3 (positions 0 to 2). It has three elements, so the median-of-three sorts them (they are already in order) and the recursion ends in this branch.
The right part is 6 5 7 8 (positions 4 to 7).
| Action | Part | Comment |
|---|---|---|
| Median-of-three of 6, 5, 8 (positions 4, 5, 7) | 5 6 7 8 | Sorted among themselves; the pivot is 6. |
| Hide the pivot at the end | 5 8 7 6 | |
i stops at 8 (position 5), j stops at 5 (position 4): they cross | 5 8 7 6 | No swap. |
| Place the pivot at position 5 | 5 6 7 8 |
Then the left part 5 has a single element (nothing to do), and the right part 7 8 has two elements, already sorted by its median-of-three. The vector is sorted: 1 2 3 4 5 6 7 8.
The recursive calls form this tree (each node shows the part it sorts):
Only two partitions were needed. The median-of-three chose good pivots, and the parts with three elements or fewer were finished without further recursion.
Analysis
Partitioning a part of elements costs : each element is compared with the pivot about once, as i and j sweep the part. The total cost therefore depends on how balanced the partitions are.
- 🟢 Best case
- 🔴 Worst case
- 🟡 Average case
The pivot always divides the part into two halves. Read the cost directly from the code: sorting elements means partitioning them (about steps) and then sorting two halves of elements. If is the time to sort elements, that sentence written as an equation is:
It is not magic: it is the code, described in one line. To see what it adds up to, follow it with :
| Level | Parts | Size of each part | Partition work at the level |
|---|---|---|---|
| 0 | 1 | 16 | 16 |
| 1 | 2 | 8 | 16 |
| 2 | 4 | 4 | 16 |
| 3 | 8 | 2 | 16 |
| Total | 64 |
At every level the parts together contain the elements, so every level costs about . The sizes halve until they reach 1, which takes levels (). Total: per level times levels, :
The divide and conquer chapter turns this reasoning into a general formula for this kind of equation, called a recurrence.
The pivot is always the smallest (or largest) element of its part, so one of the parts is empty and the other one has elements. The tree has levels, with parts of sizes :
In words: sorting elements costs partitioning them (about steps) plus sorting the that remain on one side:
The total number of comparisons is about , as bad as the simple algorithms. With the first element as pivot, this happens precisely when the data is already sorted (or reverse-sorted). With median-of-three it is much harder to trigger, but specially constructed inputs can still cause it.
When the pivot is chosen at random (or the input is random), partitions are not perfectly balanced, but they are "reasonably" balanced most of the time. A detailed analysis shows that the average number of comparisons is about : only about 39 % more than the best case. The average case is .
We checked the effect of the pivot by counting comparisons with (the theoretical value of is about 9,966):
| Pivot | Sorted | Random | Reverse |
|---|---|---|---|
| Median-of-three | 9,541 comparisons, depth 9 | 15,370 comparisons, depth 18 | 10,539 comparisons, depth 9 |
| First element | 499,500 comparisons, depth 999 | 12,563 comparisons, depth 25 | 499,500 comparisons, depth 999 |
With the first element as pivot, sorted and reverse inputs trigger the worst case: exactly comparisons and a recursion as deep as the array is long. With median-of-three, the same inputs are actually the easiest ones.
Properties
| Property | Quicksort |
|---|---|
| Best case | |
| Average case | |
| Worst case | |
| Extra memory | The recursion stack: in the best and average cases, in the worst case |
| Stable | No: partitioning exchanges distant elements |
| Adaptive | Not in general |
In practice, Quicksort is very fast for : its inner loops are very simple and it accesses memory sequentially, which modern processors handle very efficiently. For very small parts, simple algorithms are faster.
ProofThe average cost of QuicksortPractical Weaknesses and Improvements
Recursion depth
In the worst case, the recursion reaches a depth of , which can exhaust the call stack. The standard fix is to recurse only on the smaller part and handle the larger part with a loop. Since the smaller part has at most half the elements, the depth is then at most , whatever the pivots.
Many repeated keys
Look at the scanning loops: i advances while elements[i] <= pivot, and j retreats while elements[j] >= pivot. If all the elements are equal, i runs to the end of the part, the pivot is placed at the last position, and every partition is completely unbalanced: quadratic time. We measured it with the course implementation: sorting 20,000 equal elements took about 97 ms (and 25 ms for 10,000: the time quadruples when doubles), versus about 2 ms for 20,000 random elements. With 50,000 equal elements, the recursion is so deep that it ends with a StackOverflowError.
Arrays with many repeated keys are very common (sorting people by age, or orders by status). Two well-known solutions:
- stop both scans at elements equal to the pivot (
<and>instead of<=and>=) and exchange them; this splits runs of equal keys evenly between both sides; - use a three-way partition (the "Dutch national flag" problem, studied by Dijkstra), which divides the part into elements smaller than, equal to and greater than the pivot, and recurses only on the first and last groups. With many equal keys, it becomes much faster than standard Quicksort.
Small parts
For parts of fewer than about 10 to 20 elements, the overhead of recursion outweighs its benefits. Many implementations stop the recursion at that size and finish with insertion sort, which is very fast on small and almost sorted arrays (the parts are already roughly in their final zones).
Guaranteeing
Even with a good pivot strategy, an adversary can construct inputs that make Quicksort quadratic. Introsort monitors the recursion depth and, if it exceeds a multiple of , switches to another algorithm that guarantees . It is used in several standard libraries. Java's Arrays.sort for primitive types uses a highly tuned dual-pivot Quicksort, which partitions into three parts using two pivots.
Parallelism
After a partition, the two parts are completely independent, so they can be sorted in parallel by different threads. This makes Quicksort a natural candidate for the parallel algorithms chapter.
🧠 Checkpoint: Which pivot strategy?
Question: A program sorts, every night, a list of transactions that is usually already sorted except for a few hundred new transactions appended at the end. Which pivot strategy would you avoid? Is Quicksort even the best choice here?
Answer: Avoid the first or last element: on almost sorted data, they produce extremely unbalanced partitions, with quadratic time and a risk of stack overflow. Median-of-three or the central element work well. But for almost sorted data, an adaptive algorithm is better still: insertion sort (if there are very few misplaced elements) or an algorithm that detects sorted runs, such as Mergesort-based TimSort, which Java uses for objects.
Measurements
Times in milliseconds, without optimization (-Xint), with the course implementation:
| Sorted | Random | Reverse | |
|---|---|---|---|
| 4,000 | 0.7 | 1.9 | 0.9 |
| 8,000 | 1.6 | 3.7 | 1.8 |
For random elements, Quicksort takes about 4 ms, while insertion sort takes 329 ms and bubble sort more than a second. And the gap grows with : doubling the size roughly doubles the time of Quicksort (a little more, because of the factor), while it quadruples the time of the simple algorithms.
- Taking the first element as pivot. Sorted or reverse-sorted inputs then give ; use the median of three.
- Including the pivot in a recursive call. A part may not shrink and the recursion never ends; exclude the pivot.
- Reading the average case as a guarantee. The worst case is still .
- Ignoring the recursion depth. In the worst case it reaches ; recursing first on the smaller part keeps it in .
Summary
- Quicksort partitions the vector around a pivot, which ends in its final position, and sorts both parts recursively.
- The pivot choice is crucial: the first or last element is cheap but disastrous on sorted data; median-of-three is a good compromise; a random pivot makes the expected cost for every input.
- Best and average cases: . Worst case: . It is in place (apart from the recursion stack) but not stable.
- Practical improvements: recurse on the smaller part (stack depth ), handle repeated keys (three-way partition), switch to insertion sort for small parts, and fall back to another algorithm when the recursion gets too deep (Introsort).
Practice
- ✍️ Trace it. Sort 5 6 1 3 9 8 7 4 2 by hand with the course version of Quicksort (median-of-three, hiding the pivot at the end). Draw the tree of recursive calls.
- 🔴 Find the worst case. Using the first element as pivot, which inputs of size 8 make Quicksort perform the maximum number of comparisons? Implement this version and count the comparisons for sorted data with .
- 🟰 Repeated keys. Measure the course implementation on arrays of equal elements and on arrays with only 3 different values, for increasing sizes. Then implement a three-way partition and repeat the measurements.
- 📏 Limit the stack. Modify the implementation so that it recurses only on the smaller part. Check, by counting the maximum depth, that it never exceeds .
- 🧩 Hybrid. Add a threshold below which parts are sorted with insertion sort. Measure the total time for . Which threshold works best on your machine?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.