Algorithm Visualiser by Tsvetozar Biserov

Dual-Pivot Quick Sort

  • Ω( n log n )
  • Θ( n log n )
  • O( n2 )
  • space O( log n )

Dual-pivot quick sort chooses two pivots, sorts them into a smaller and a larger one, and splits the range into three parts in a single sweep: values below the first pivot, values between the two, and values from the second pivot up. The pivots here come from the one-third and two-thirds positions of the range, and the three parts are then sorted recursively.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How dual-pivot quick sort works

For 5, 2, 6, 1, 4, 3 the range is positions 0 to 5, so one third of its length rounds down to 1. The code swaps the first slot with index 1 and the last slot with index 4, giving 2, 5, 6, 1, 4, 3 and then 2, 5, 6, 1, 3, 4. Those are the first two rows of the table. The slot at each end now holds a pivot, 2 on the left and 4 on the right, and they are already in order, so no third swap is needed.

The sweep covers the four values between them, 5, 6, 1, 3. The 5 is not smaller than 2 and not smaller than 4, so it belongs in the high part. Before swapping, the code checks the end of the unexamined zone; the 3 there is not larger than 4, so the 5 swaps with it and the array reads 2, 3, 6, 1, 5, 4. The 3 that arrived is between the pivots and stays. The 6 also belongs high and trades places with the 1, giving 2, 3, 1, 6, 5, 4. That 1 is smaller than the left pivot, so it swaps again, into the low zone, and the array reads 2, 1, 3, 6, 5, 4.

Two swaps then drop the pivots into their final slots. Moving the first pivot next to the low value gives 1, 2, 3, 6, 5, 4, and moving the right pivot into the boundary of the high part gives 1, 2, 3, 4, 5, 6. That is the seventh row, and the array is sorted after one pass. The three recursive calls find a single element, a single element, and the pair 5, 6, which is already in order. The run used 12 comparisons and 7 swaps, fewer comparisons than plain or three-way quick sort on this input, though on six numbers that says little.

Dual-Pivot Quick Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Swap indexes 0 and 1 2 5 6 1 4 3
2 Swap indexes 5 and 4 2 5 6 1 3 4
3 Swap indexes 1 and 4 2 3 6 1 5 4
4 Swap indexes 2 and 3 2 3 1 6 5 4
5 Swap indexes 2 and 1 2 1 3 6 5 4
6 Swap indexes 0 and 1 1 2 3 6 5 4
7 Swap indexes 5 and 3 1 2 3 4 5 6

All 7 changes are shown.

Pseudocode

sort(lo, hi)
  if lo >= hi
    return
  p = a[lo], q = a[hi]
  if q < p
    swap p and q
  less = lo + 1, great = hi - 1, k = lo + 1
  while k <= great
    if a[k] < p
      swap a[k], a[less]
      less = less + 1
    else if a[k] > q
      while a[great] > q and k < great
        great = great - 1
      swap a[k], a[great]
      great = great - 1
      if a[k] < p
        swap a[k], a[less]
        less = less + 1
    k = k + 1
  place p at less - 1 and q at great + 1
  sort(lo, less - 2)
  sort(less, great)
  sort(great + 2, hi)

Why these complexities

Each pass reads each element once and compares it with the first pivot, and sometimes with the second as well, so a level costs between n and 2n comparisons. Three parts per pass mean fewer levels than the two-way version, about log₃ n instead of log₂ n, which roughly cancels the extra comparisons and leaves O(n log n). On 1000 shuffled values this implementation used 11,254 comparisons, close to the 11,650 of the two-way version, but only 3,508 swaps against 5,402.

That swap gap owes much to the Lomuto partition of the two-way version, which swaps often. Wild and Nebel's analysis of Yaroslavskiy's scheme found about 5 percent fewer comparisons than classic quick sort but more swaps, and later work attributed most of the real speed gain to fewer cache misses, which a step counter cannot show. The worst case is O(n²). Because the pivots always come from the same fixed positions, sorted and reversed input split evenly, and 1000 sorted values took only 7,740 comparisons and 600 swaps, but an input designed to put extreme values at those probe positions can still force one-element splits.

When the two pivots turn out to be equal, everything between them is equal as well, so the code switches to the three-way partition for that range; 1000 equal values cost 2,002 comparisons. Memory use is the weak point of this version. It recurses into all three parts with no loop, so on typical data the stack is O(log n), but a crafted input can make it grow linearly. The sort is in place, not stable, and not adaptive.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 141 0 69
Already sorted 116 0 16
Reversed 138 0 32
Few distinct values 164 0 38

When to use it

Use it, or the library function built on it, when you sort large arrays of primitive values and want the speed of a tuned quick sort. For objects that must keep their order, use a stable sort instead.

Frequently asked questions

Why use two pivots?

Each pass splits the range into three parts instead of two, which means fewer passes over the data and fewer cache misses.

Where is it used?

A variant sorts primitive arrays in Java. Vladimir Yaroslavskiy proposed the algorithm.

Is dual-pivot quick sort stable?

No. The partition moves elements across long distances, so equal elements can change order.

What does it do when the two pivots are equal?

After ordering the pivots, the code tests whether the first is strictly smaller than the second. If not, they are equal and everything between them must be equal too, so a middle part would just be wasted work. It then runs the three-way partition on that range and recurses only into the smaller and larger sides. Repeated keys are therefore handled in about two comparisons per element.

Does it really make fewer comparisons than the two-way version?

Barely. On 1000 shuffled values it made 11,254 comparisons, against 11,650 for quick sort with a median-of-three pivot, and the gap depends on the data. The clearer difference is in swaps, 3,508 against 5,402 here. Most of the practical speed-up reported for Java comes from memory access, which a count of comparisons and swaps cannot capture.

Background

Vladimir Yaroslavskiy proposed the algorithm in 2009 and posted it to the Java core libraries mailing list. After benchmarking and review by Jon Bentley and Joshua Bloch it replaced the older tuned quick sort behind Arrays.sort for primitive arrays in Java 7, released in 2011. Later Java versions revised the implementation again, but the two-pivot core stayed.

It was a surprise to many that a second pivot helped at all, because earlier analysis suggested no gain from multiple pivots. Sebastian Wild and Markus Nebel showed in 2012 that the comparison count improves only slightly, and a 2014 study by Kushagra, Lopez-Ortiz, Munro and Qiao traced the speed to memory behaviour: fewer passes over the data mean fewer cache misses on large arrays.

References

  • Wild and Nebel, Average Case Analysis of Java 7's Dual Pivot Quicksort, ESA 2012
  • Kushagra, Lopez-Ortiz, Munro, Qiao, Multi-Pivot Quicksort: Theory and Experiments, ALENEX 2014
  • Knuth, The Art of Computer Programming, vol. 3, section 5.2.2

Compare with

Algorithm Average time Worst time
Bubble Sort Θ( n2 ) O( n2 )
Cocktail Shaker Sort Θ( n2 ) O( n2 )
Comb Sort Θ( n2 ) O( n2 )
Gnome Sort Θ( n2 ) O( n2 )
Odd-Even Sort Θ( n2 ) O( n2 )
Quick Sort Θ( n log n ) O( n2 )
3-Way Quick Sort Θ( n log n ) O( n2 )
Big O notation
Best time Ω( n log n ) good
Average time Θ( n log n ) good
Worst time O( n2 ) poor
Worst space O( log n ) good

Properties

Stable
No
In place
Yes
Adaptive
No
Comparison-based
Yes