Quicksort
Sort an array by putting one pivot value in its final place at a time, then sorting the values on each side of it.
Sort an array of integers numsnums
Example
Output: [10, 30, 40, 50, 70, 80, 90]
The Idea
Picture a teacher putting a pile of marked exam papers in order of score. Instead of comparing every paper with every other one, she picks one paper, scored 70, and puts it on the table. Each paper with a lower score goes to its left, each with a higher score to its right. Neither pile is in order yet, but the paper scored 70 already sits exactly where it belongs.
Do the same with the example. The value we pick is called the pivot, and here it is the last value, 70. Four values are smaller than 70: 10, 30, 40 and 50. So in the sorted array 70 comes fifth, at index 4, whatever order those four end up in. Moving the smaller values to the pivot's left and the larger ones to its right is called partitioning.
That leaves two piles, 10, 30, 40, 50 on the left and 90, 80 on the right. How do they get sorted? Each pile is a smaller array of the same kind, so the same trick works on it: pick its last value as the pivot and partition again. The picture follows the example through every partition, one row per round.
In the row labelled "partition around 70", the values smaller than 70 fill indexes 0 to 3, the larger ones fill 5 and 6, and 70 is orange at index 4. In the next row, the left range uses its last value, 50, as pivot. Every other value there is smaller, so 50 stays at index 3. The right range, 90 and 80, uses 80 as pivot, and the two values swap.
In the row labelled "partition around 40; 90 is alone", the range holding just 90 needs no work: one value is always in order. The last row does the same for 30 and then 10. By then every value has been a pivot or alone in its range, so every value is in its final spot.
So each partition fixes one value for good and splits the rest into two smaller ranges that never mix again. Nothing has to be merged at the end. The method that sorts the whole array sorts indexes 0 to 3 by calling itself on just that range, and a method that calls itself on smaller ranges like this is recursive.
Look at the left range once more. 50, then 40, then 30 were each the largest value in its range, so each partition split off one value and left the rest in one piece. Those three rounds did little. How evenly the pivots split their ranges decides how fast quicksort is.
Solution Approach
The code has four decisions to make: how to partition a range in place, when the recursion stops, which value to take as the pivot, and what happens to equal values. There is also an optional second way to partition, with two indexes that move toward each other.
Partitioning a range in place
How can values move to the correct side of the pivot without a second array? One index, istorestore
When nums[i]storestorestore[10, 30, 80, 90, 40, 50, 70][10, 30, 40, 50, 80, 90, 70]store
A last swap puts the pivot 70 at index 4, where 80 was, and the array reads [10, 30, 40, 50, 70, 90, 80]
Where the recursion stops
When is a range already sorted? When it holds one value, like the range with just 90, or none at all. Partitioning around 50 left no values to its right, so the range after it runs from index 4 to index 3, which is empty. The stop check is therefore left >= rightleftright
After a partition puts the pivot at index pleftp - 1p + 1right
Choosing the pivot
Why not always take the last value? It is the simplest choice, but it goes badly when the array is already sorted. Then the last value is the largest in every range, and each partition splits off one value, as 50, 40 and 30 did in the picture. A range of 1,000 values costs 999 comparisons, the next 998, and so on: 499,500 in total.
An even split halves each range instead, so the ranges are done after about log2 n rounds of halving. Picking a random index and swapping its value to the end before partitioning makes a sorted array no worse than any other. A version of the code with that swap sorted the same 1,000 sorted values with 11,454 comparisons. Taking the middle value, or the middle one of the first, middle and last values, are other common choices.
Equal values and stability
What if many values are the same? The check nums[i] <= pivot
Equal values also raise a second question: do they keep their order? Think of cards marked 2a, 2b and 1c, sorted by their number only. A sort that keeps 2a before 2b is called stable. One partition of [2a, 2b, 1c][1c, 2b, 2a]int
Optional: Hoare's partition
Tony Hoare, who invented quicksort, partitioned with two indexes that move toward each other. Here the pivot is the middle value of the range. Index ij
static int hoarePartition(int[] nums, int left, int right) {
int pivot = nums[left + (right - left) / 2]; // the middle value is the pivot
int i = left - 1;
int j = right + 1;
while (true) {
do { i++; } while (nums[i] < pivot); // a value that belongs on the right
do { j--; } while (nums[j] > pivot); // a value that belongs on the left
if (i >= j) {
return j; // nums[left..j] <= nums[j+1..right]
}
swap(nums, i, j);
}
}
When the indexes cross, every value from leftjjjleftjj + 1right
Java Solution
The class sorts with the Lomuto partition and the last value as pivot, in these steps:
- First,
callssort(nums) , so the first range is the whole array, from indexquickSort(nums, 0, nums.length - 1) to indexleft .right - In
, return at once whenquickSort , because a range of one value or none is already sorted.left >= right - Otherwise call
. It takespartition(nums, left, right) and setspivot = nums[right] . A loop movesstore = left fromi toleft . Each value at most the pivot goes to positionright - 1 with the helperstore , which exchanges the values at two indexes, andswap moves on.store - After the loop,
swaps the pivot into positionpartition and returns that index, whichstore keeps asquickSort .p - Finally
calls itself onquickSort toleft and onp - 1 top + 1 .right
The static field comparisonspartitionmain
The maincount
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
static long comparisons; // counted only to show the cost
public static void sort(int[] nums) {
quickSort(nums, 0, nums.length - 1);
}
private static void quickSort(int[] nums, int left, int right) {
if (left >= right) {
return; // 0 or 1 value: already sorted
}
int p = partition(nums, left, right); // nums[p] is now in its final place
quickSort(nums, left, p - 1);
quickSort(nums, p + 1, right);
}
// The last value is the pivot; returns the index where the pivot ends up
private static int partition(int[] nums, int left, int right) {
int pivot = nums[right];
int store = left; // nums[left..store-1] are <= pivot
for (int i = left; i < right; i++) {
comparisons++;
if (nums[i] <= pivot) {
swap(nums, i, store);
store++;
}
}
swap(nums, store, right); // the pivot goes right after them
return store;
}
private static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
private static void count(String name, int[] nums) {
comparisons = 0;
sort(nums);
System.out.println(name + ": " + comparisons + " comparisons");
}
public static void main(String[] args) {
int[][] tests = {{10, 80, 30, 90, 40, 50, 70}, {}, {5}, {3, 1, 3, 2, 1}, {-4, 7, 0, -4, 2}};
for (int[] nums : tests) {
String before = Arrays.toString(nums);
sort(nums);
System.out.println(before + " -> " + Arrays.toString(nums));
}
int n = 1000;
int[] sorted = new int[n];
int[] reversed = new int[n];
int[] equal = new int[n];
int[] shuffled = new int[n];
for (int i = 0; i < n; i++) {
sorted[i] = i;
reversed[i] = n - 1 - i;
equal[i] = 7;
shuffled[i] = i;
}
Random random = new Random(42); // fixed seed: same order every run
for (int i = n - 1; i > 0; i--) {
swap(shuffled, i, random.nextInt(i + 1));
}
count("1000 values, shuffled", shuffled);
count("1000 values, already sorted", sorted);
count("1000 values, in reverse order", reversed);
count("1000 values, all equal", equal);
}
}
Running it prints:
[10, 80, 30, 90, 40, 50, 70] -> [10, 30, 40, 50, 70, 80, 90]
[] -> []
[5] -> [5]
[3, 1, 3, 2, 1] -> [1, 1, 2, 3, 3]
[-4, 7, 0, -4, 2] -> [-4, -4, 0, 2, 7]
1000 values, shuffled: 11482 comparisons
1000 values, already sorted: 499500 comparisons
1000 values, in reverse order: 499500 comparisons
1000 values, all equal: 499500 comparisons
The example comes out as [10, 30, 40, 50, 70, 80, 90][]left = 0right = -1[5]quickSort
Now compare the last four lines. The shuffled 1,000 values took 11,482 comparisons. Sorted, reversed and all-equal input each took 499,500, which is 1,000 × 999 / 2: every partition split off a single value. In reversed order the last value is the smallest in each range, so the split is just as lopsided, only on the other side.
The original implementation,
Complexity
Each round of partitions compares the values in its ranges with their pivots once, so the cost depends on how many rounds the pivots' splits need.
- Best time: O(n log n), because when every pivot is the middle value of its range, the ranges halve each round and about log2 n rounds of at most n comparisons are enough. One such input is
, sorted with 10 comparisons where the example needs 13.[10, 30, 20, 60, 50, 70, 40] - Average time: O(n log n), because on values in random order most pivots land far enough from the ends of their ranges, as the 11,482 comparisons for the shuffled 1,000 values show.
- Worst time: O(n2), because on sorted, reversed or all-equal input each partition of this code splits off one value, so the ranges shrink by one and the comparisons add up to n(n - 1) / 2.
- Space: O(log n) on average and O(n) in the worst case, because the array is sorted in place and the only extra memory is the chain of nested
calls. That chain was 25 calls deep for the shuffled 1,000 values and 1,000 deep for the sorted ones.quickSort
When equal values must keep their order,