Dual-Pivot QuickSort in Java
Learn how Dual-Pivot QuickSort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
Dual-Pivot QuickSort is a divide-and-conquer sorting algorithm. Where classic QuickSort splits the array around one pivot, this version picks two pivots and splits the array into three parts: values below the smaller pivot, values between the two pivots, and values above the larger pivot. Each part is then sorted the same way, recursively.
Three ideas carry the whole algorithm:
- Two pivots: the first and last values of the range, ordered so that
pivot1is not larger thanpivot2. - Three-way partition: one pass over the range sorts every value into the left part (
< pivot1), the middle part (between the pivots) or the right part (> pivot2). - Three pointers:
pivot1Endmarks the end of the left part,highthe start of the right part, andlowwalks through the values still to be placed.
Vladimir Yaroslavskiy published Dual-Pivot QuickSort in 2009, and since Java 7 it has been the algorithm behind Arrays.sort() for primitive arrays such as int[] and double[]. It makes about the same number of comparisons as classic QuickSort, but it splits each range into smaller pieces and scans memory fewer times, which makes it faster on modern hardware. The JDK version adds more on top, such as picking the pivots from a sample of five values and switching to insertion sort for small ranges.
This article uses the basic Dual-Pivot QuickSort with the end values as pivots: the first and last values of each range become the two pivots, and one pass partitions the values between them.
Performance Characteristics
Like classic QuickSort, Dual-Pivot QuickSort is very fast on average, but its speed and memory use depend on how evenly the two pivots split each range.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n \log n)$ | The pivots split every range into parts of similar size |
| Average | $O(n \log n)$ | Random or mixed input |
| Worst | $O(n^2)$ | The pivots are the smallest and largest values of their range, e.g. an already sorted array |
Why $n \log n$? Each partition pass touches every value in its range once ($n$ work per level), and splitting each range into three parts gives about $\log_3 n$ levels. When both pivots are the extremes of their range, only two values are placed per pass, and the levels grow to about $n / 2$.
Taking the first and last values as pivots is what makes sorted input the worst case. The JDK avoids this by choosing the pivots from five values spread through the range, so the pivots are much more likely to fall near the middle.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(\log n)$ on average for the recursion stack, $O(n)$ worst case |
| In place | Yes |
| Stable | No (swaps move values past equal values) |
Algorithm (Pseudo Code)
Dual-Pivot QuickSort starts by looking at the first and last values of the range. If the first is larger, they swap, so the first value becomes the smaller pivot and the last value the larger pivot. Then a pointer walks from left to right through the values between them. A value smaller than the first pivot is swapped into the left part. A value at least as large as the second pivot is swapped with a value from the right end, so it joins the right part; the value that comes back is checked again. Anything else stays in the middle. When the pointer meets the right part, the two pivots are swapped into the gaps between the three parts.
Both pivots are now in their final positions. The same steps run on the left part, the middle part and the right part, and those split again, until every part holds one value or none, and the array is sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
dualPivotQuicksort(array, left, right):
if left < right:
[p1, p2] = partition(array, left, right)
dualPivotQuicksort(array, left, p1 - 1)
dualPivotQuicksort(array, p1 + 1, p2 - 1)
dualPivotQuicksort(array, p2 + 1, right)
partition(array, left, right):
if array[left] > array[right]: swap(left, right)
pivot1 = array[left], pivot2 = array[right]
pivot1End = left + 1, low = left + 1, high = right - 1
while low <= high:
if array[low] < pivot1:
swap(low, pivot1End), pivot1End++
else if array[low] >= pivot2:
while low < high and array[high] > pivot2: high--
swap(low, high), high--
if array[low] < pivot1: swap(low, pivot1End), pivot1End++
low++
pivot1End--, high++
swap(left, pivot1End), swap(right, high)
return [pivot1End, high]
After partition, the values left of pivot1 are smaller than it, the values right of pivot2 are at least as large as it, and the values between the pivots lie between the two pivot values.
The Java code below returns
[low, high]instead of[pivot1End, high]. The partition itself is the same, but the recursion changes, as the warning in thepartitionsection explains.
Visualization
The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.
Each step shows the array, the pointers and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with a new random order.
- Pointers: E is
pivot1End, the end of the left part, L islow, the next value to place, and H ishigh, the start of the right part. - Colours: the two pivots are amber, the two values being swapped are salmon, and values that are in their final place turn green.
- Split: the gray bars mark the two indices returned by
partition. - Return pivot1End: tick Return pivot1End to see the three-way recursion the algorithm is designed for, instead of what the Java code does.
Java Code
The implementation is a DualPivotQuickSort class with one public method, sort, and two private methods: dualPivotQuicksort handles the recursion, and partition does the three-way split with the pointer work. Four small helpers, swap, less, greater and greaterOrEqual, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
DualPivotQuickSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
@Override
public <T extends Comparable<T>> T[] sort(final T[] array) {
if (array.length <= 1) {
return array;
}
dualPivotQuicksort(array, 0, array.length - 1);
return array;
}
sort is the entry point. It accepts an array of any Comparable type, such as Integer or String. An array with zero or one value is already sorted and comes straight back. Otherwise it calls dualPivotQuicksort on the full range, from index 0 to the last index, and returns the same array, now sorted in place.
dualPivotQuicksort
1
2
3
4
5
6
7
8
9
private static <T extends Comparable<T>> void dualPivotQuicksort(final T[] array, final int left, final int right) {
if (left < right) {
final int[] pivots = partition(array, left, right);
dualPivotQuicksort(array, left, pivots[0] - 1);
dualPivotQuicksort(array, pivots[0] + 1, pivots[1] - 1);
dualPivotQuicksort(array, pivots[1] + 1, right);
}
}
dualPivotQuicksort is the recursive part. When the range has fewer than two values, it is already sorted and there is nothing to do. Otherwise partition splits the range and returns two indices in an int[], and the method recurses on the three parts around them: left of pivots[0], between pivots[0] and pivots[1], and right of pivots[1]. The values at the two indices themselves are skipped, because a pivot is already in its final place.
partition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private static <T extends Comparable<T>> int[] partition(final T[] array, int left, final int right) {
if (SortUtils.greater(array[left], array[right])) {
SortUtils.swap(array, left, right);
}
final T pivot1 = array[left];
final T pivot2 = array[right];
int pivot1End = left + 1;
int low = left + 1;
int high = right - 1;
while (low <= high) {
if (SortUtils.less(array[low], pivot1)) {
SortUtils.swap(array, low, pivot1End);
pivot1End++;
} else if (SortUtils.greaterOrEqual(array[low], pivot2)) {
while (low < high && SortUtils.greater(array[high], pivot2)) {
high--;
}
SortUtils.swap(array, low, high);
high--;
if (SortUtils.less(array[low], pivot1)) {
SortUtils.swap(array, low, pivot1End);
pivot1End++;
}
}
low++;
}
pivot1End--;
high++;
SortUtils.swap(array, left, pivot1End);
SortUtils.swap(array, right, high);
return new int[] {low, high};
}
partition does the real work. It first makes sure the value at left is not larger than the value at right, and takes them as pivot1 and pivot2. The values between them are then sorted into three parts: [left + 1 .. pivot1End - 1] holds values below pivot1, [pivot1End .. low - 1] holds values between the pivots, and [high + 1 .. right - 1] holds values of pivot2 and above. low walks through the unplaced values in [low .. high], and each one is swapped into the left part, swapped into the right part, or left in the middle.
When low passes high, pivot1End and high each step back by one, onto the last slot of the left part and the first slot of the right part, and the two pivots are swapped into those slots. Now pivot1 sits at pivot1End and pivot2 at high, both in their final places.
Two details are worth noticing:
- When a value of
pivot2or above is found, the inner loop first moveshighpast values that are already larger thanpivot2, so they aren’t swapped for nothing. The value that comes back fromhighhasn’t been checked yet, so it gets one more test againstpivot1. If it is larger thanpivot1, it stays in the middle. - Values equal to
pivot1stay in the middle part, while values equal topivot2go to the right part. The parts never overlap, so each value is placed exactly once.
The comment in the Java source says “Return the indices of the pivots”, but the method returns
{low, high}, not{pivot1End, high}. When the loop ends,lowis just right ofhigh, so afterhigh++it points atpivot2(or one past it), never atpivot1. As a result, the first recursive call sorts[left .. low - 1], which still includespivot1and the whole middle part, and the second call is always empty. The array still ends up sorted, because the values left ofpivot2are all smaller than or equal to it, but each partition only finishes one pivot. The sort behaves like single-pivot QuickSort aroundpivot2and loses the advantage of three parts. Returningnew int[] {pivot1End, high}fixes it; tick Return pivot1End in the visualization to see the difference.
swap, less, greater and greaterOrEqual
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static <T> void swap(T[] array, int i, int j) {
if (i != j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) < 0;
}
public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) > 0;
}
public static <T extends Comparable<T>> boolean greaterOrEqual(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) >= 0;
}
These helpers from SortUtils keep partition easy to read. swap exchanges two elements, and skips the work when both indices are the same. The other three compare two elements with compareTo, so the algorithm works for any type that implements Comparable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new DualPivotQuickSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a DualPivotQuickSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects; for an int[], Arrays.sort() runs the JDK’s own Dual-Pivot QuickSort.
Summary
- Dual-Pivot QuickSort is a divide-and-conquer sort: pick two pivots, partition the range into three parts around them, then recurse on each part.
- This implementation takes the first and last values as pivots, and one pass with three pointers,
pivot1End,lowandhigh, places every value in the left, middle or right part. - After
partition, both pivots are in their final places: smaller values to the left ofpivot1, larger values to the right ofpivot2, and the values in between in the middle. - It runs in $O(n \log n)$ on average and $O(n^2)$ in the worst case, such as an already sorted array, and it sorts in place but is not stable.
- The Java code returns
lowinstead ofpivot1End, so it recurses on two parts, not three; it is still correct, but slower than the design. For real code, useArrays.sort(), which runs a tuned Dual-Pivot QuickSort on primitive arrays, or a stable sort such as TimSort when equal values must keep their order.
