3-Way Quick Sort
- Ω( n )
- Θ( n log n )
- O( n2 )
- space O( log n )
Three-way quick sort treats the pivot as a value, not a position. Each pass sweeps the range once and leaves three bands behind: everything smaller than the pivot, everything equal to it, and everything larger. Only the outer two bands are sorted further. Duplicates therefore cost almost nothing, while arrays of distinct keys pay a small extra price per element.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- 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 3-way quick sort works
On 5, 2, 6, 1, 4, 3 the pivot is picked the same way as in the plain version: the first, middle and last elements are put in order. Swapping 5 with 3 and then 6 with 5 gives 3, 2, 5, 1, 4, 6, and the 5 in the middle is read as the pivot value. Unlike the two-way version, nothing is moved to the end. The sweep uses three markers: lt, the start of the equal band; i, the element being examined; and gt, the end of the unexamined part.
The 3 and the 2 are smaller than 5, so lt and i advance together and nothing is swapped. The 5 itself is equal and is simply stepped over, which leaves lt behind it. Then the 1 arrives and is smaller, so it swaps with the first equal element, giving 3, 2, 1, 5, 4, 6; the 4 does the same, giving 3, 2, 1, 4, 5, 6. Finally the 6 is larger than the pivot and is already sitting at gt, so it needs no swap and gt shrinks past it. The single 5 at index 4 is the whole equal band, and it will never be looked at again.
The left band 3, 2, 1, 4 is sorted next. Ordering its first, middle and last elements swaps 3 and 2, giving 2, 3, 1, 4, 5, 6, with 3 as the pivot. The 2 is skipped, the 3 is equal, the 1 swaps with that 3 to give 2, 1, 3, 4, 5, 6, and the 4 is already at the end. One last swap fixes the pair 2, 1. The whole run takes 7 swaps, fewer than the 13 of the two-way version, but 27 comparisons instead of 18, because every element that is not smaller than the pivot is tested a second time to see whether it is larger or equal.
| Step | Change | Array after |
|---|---|---|
| 1 | Swap indexes 5 and 0 | 3 2 6 1 4 5 |
| 2 | Swap indexes 5 and 2 | 3 2 5 1 4 6 |
| 3 | Swap indexes 2 and 3 | 3 2 1 5 4 6 |
| 4 | Swap indexes 3 and 4 | 3 2 1 4 5 6 |
| 5 | Swap indexes 1 and 0 | 2 3 1 4 5 6 |
| 6 | Swap indexes 1 and 2 | 2 1 3 4 5 6 |
| 7 | Swap indexes 1 and 0 | 1 2 3 4 5 6 |
All 7 changes are shown.
Pseudocode
quicksort(lo, hi)
if lo >= hi
return
pivot = median of a[lo], a[mid], a[hi]
lt = lo, i = lo, gt = hi
while i <= gt
if a[i] < pivot
swap a[lt], a[i]
lt = lt + 1, i = i + 1
else if a[i] > pivot
swap a[i], a[gt]
gt = gt - 1
else
i = i + 1
quicksort(lo, lt - 1)
quicksort(gt + 1, hi)
Why these complexities
With distinct keys this behaves like any quick sort: one sweep per level, about log₂ n levels on average, so O(n log n). The constant is higher, though. An element that is not smaller than the pivot needs a second comparison to tell larger from equal. On 1000 shuffled values the count was 18,098 comparisons, against 11,650 for the two-way version, with 6,770 swaps.
The best case comes from duplicates. When all keys are equal, the first sweep finds that every element belongs to the middle band, the recursion stops at once, and the whole sort is one pass: 2,003 comparisons and no swaps for 1000 equal values, where the two-way version needed 502,497. With only four distinct values among 1000 elements it took 3,512 comparisons. With k distinct keys the work is bounded by roughly n times k, which is linear when k is a small constant.
The worst case is still O(n²), because a poor sequence of pivots can still shave off one element at a time. Sorted input is an unexpected weak spot here: 1000 sorted values took 38,873 comparisons and 17,388 swaps, more than shuffled input, since every element larger than the pivot is swapped with the end marker and that half ends up rotated, with its smallest value moved to the far end. The stack stays at O(log n) because the code recurses into the smaller outer band and loops on the larger one. The sort is not stable, and it is adaptive only to repeated values, not to existing order.
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 | 318 | 0 | 107 |
| Already sorted | 284 | 0 | 86 |
| Reversed | 250 | 0 | 68 |
| Few distinct values | 124 | 0 | 27 |
When to use it
Use it when the data has many duplicate values, such as grades, ages or status codes. It also behaves well on data with a few distinct keys, where plain quick sort slows down.
Frequently asked questions
What does the three-way partition do?
It splits the range into elements smaller than, equal to and larger than the pivot. Only the smaller and larger parts are sorted further.
Why is it linear with few distinct values?
Every element equal to the pivot is final after one partition, so the recursion depth is bounded by the number of distinct values.
Is it stable?
No. The partition swaps elements across the array and does not keep the original order of equals.
Why does it use more comparisons than plain quick sort on distinct keys?
Each element that is not smaller than the pivot is compared a second time to separate larger from equal. When keys are distinct, equal never happens, so that second test is wasted work. On 1000 shuffled values it came to about 55 percent more comparisons than the two-way version. The cost is repaid as soon as duplicates are common.
What do lt, i and gt mean during the partition?
They split the range into four zones. Positions before lt hold smaller values, positions from lt up to just before i hold values equal to the pivot, positions after gt hold larger values, and positions from i to gt are still unexamined. The sweep ends when i passes gt, at which point lt and gt mark the equal band that needs no further sorting.
Background
The partition comes from Edsger Dijkstra's Dutch national flag problem, which asks how to sort a row of red, white and blue items in a single pass using only swaps. He presented it in A Discipline of Programming in 1976. The link to quick sort is natural: replace the three colours with smaller than, equal to and larger than a pivot.
For decades most textbooks still taught the two-way partition. Jon Bentley and Douglas McIlroy argued in 1993, in a paper on building a production quality sort function, that real data is full of repeated keys and that handling them well matters. Their variant moves equal elements to the ends and swaps them back afterwards, a different mechanism from the markers used here, and it fed into the qsort of several C libraries. Robert Sedgewick later popularised the simpler flag version in his lectures and in Algorithms.
References
- Dijkstra, A Discipline of Programming, Prentice-Hall, 1976, chapter 14
- Bentley and McIlroy, Engineering a Sort Function, Software: Practice and Experience 23(11), 1993
- Sedgewick and Wayne, Algorithms, 4th edition, section 2.3
- 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 ) |
| Dual-Pivot Quick Sort | Θ( n log n ) | O( n2 ) |
| Best time | Ω( 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