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 nums into ascending order with quicksort. The values are rearranged inside nums itself, by swapping them, so no second array is needed.

Example
Input: nums = [10, 80, 30, 90, 40, 50, 70]
Output: [10, 30, 40, 50, 70, 80, 90]
Solution

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.

Quicksort on 10, 80, 30, 90, 40, 50, 70. Partitioning around 70 gives 10, 30, 40, 50, 70, 90, 80 with 70 at index 4. Then the left range is partitioned around 50 and the right range around 80, then around 40, then around 30, until the array reads 10, 30, 40, 50, 70, 80, 90.

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, i, walks from the start of the range to just before the pivot. A second index, store, marks where the next value that is not larger than the pivot should go. Everything before store is less than or equal to the pivot.

When nums[i] is at most the pivot, swap it into position store and move store one place right. In the example, 10 swaps with itself and store becomes 1. Next 80 is larger and stays. Then 30 swaps with that 80, giving [10, 30, 80, 90, 40, 50, 70]. Then 40 and 50 are swapped forward the same way, giving [10, 30, 40, 50, 80, 90, 70] with store at 4.

A last swap puts the pivot 70 at index 4, where 80 was, and the array reads [10, 30, 40, 50, 70, 90, 80], as in the row labelled "partition around 70". This way of partitioning, with one scanning index and the last value as pivot, is known as the Lomuto partition, after Nico Lomuto.

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 >= right, where left and right are the first and last index of the range.

After a partition puts the pivot at index p, the method sorts left to p - 1 and p + 1 to right. The pivot itself is never touched again.

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 sends every value equal to the pivot to its left. In an array of 1,000 sevens, each partition puts the pivot at the right end of its range and splits off one value. That is again 499,500 comparisons, and a random pivot does not help here, since every pivot is a seven.

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] around 1c swaps it with 2a and gives [1c, 2b, 2a], which a run of the partition confirmed. Quicksort is not stable. For plain int values that does not matter, since one 2 cannot be told from another.

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 i moves right until it stops on a value not smaller than the pivot, j moves left until it stops on a value not larger, and the two values swap.

Java
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 left to j is at most every value after j. The pivot need not sit at j, so the recursion sorts left to j and j + 1 to right. Values equal to the pivot stop both indexes and get spread over both sides. On the 1,000 sevens it made 11,862 comparisons with the pivot, and the sorted 1,000 values took 10,975. Its original implementation, QuicksortHoarePartition.java, is on GitHub.

Java Solution

The class sorts with the Lomuto partition and the last value as pivot, in these steps:

  1. First, sort(nums) calls quickSort(nums, 0, nums.length - 1), so the first range is the whole array, from index left to index right.
  2. In quickSort, return at once when left >= right, because a range of one value or none is already sorted.
  3. Otherwise call partition(nums, left, right). It takes pivot = nums[right] and sets store = left. A loop moves i from left to right - 1. Each value at most the pivot goes to position store with the helper swap, which exchanges the values at two indexes, and store moves on.
  4. After the loop, partition swaps the pivot into position store and returns that index, which quickSort keeps as p.
  5. Finally quickSort calls itself on left to p - 1 and on p + 1 to right.

The static field comparisons is not needed for sorting. The loop in partition adds one to it for each value it compares with the pivot, so main can show the cost.

The main method sorts the example, an empty array, one value, an array with repeats and one with negatives. Then the helper count sorts 1,000 values in four orders and prints the comparisons; the shuffle uses the fixed seed 42, so every run prints the same numbers.

Java
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:

Output
[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], the order the last row of the picture reached. For [] the first call gets left = 0 and right = -1, and for [5] both are 0, so quickSort returns at once. The repeated 1s and 3s, and the two -4s, end up side by side.

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, QuicksortLomutoPartition.java, is on GitHub.

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 [10, 30, 20, 60, 50, 70, 40], sorted with 10 comparisons where the example needs 13.
  • 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 quickSort calls. That chain was 25 calls deep for the shuffled 1,000 values and 1,000 deep for the sorted ones.

When equal values must keep their order, merge sort is stable and always takes O(n log n) time, at the cost of an extra array.