Three-Way Sort Algorithm
Three-Way Sort Algorithm(Three-Way Partitioning) is a special variant of quick sort, optimized specifically for handling arrays with a large number of duplicate elements. Its core idea is to divide the array into three parts in a single partitioning process, instead of the traditional two parts.
Three-way quick sort is a further improved version of two-way quick sort. The three-way sort algorithm divides the data to be sorted into three parts: less than v, equal to v, and greater than v, where v is the pivot value. In this way, among the three parts, the data equal to v no longer needs to be sorted in the next recursion, and the data less than v and greater than v will not have one part that is particularly large. Through this approach, the performance of the three-way quick sort algorithm is better.
Imagine you have a big bucket of mixed colored marbles, with three colors: red, white, and blue. Your task is to quickly separate them so that all red marbles are on the left, white in the middle, and blue on the right. The three-way sort algorithm is the sorting master that solves this kind of problem.
Traditional Quick Sort vs Three-Way Quick Sort
Let us use a simple table to compare the differences between the two:
| Feature | Traditional Quick Sort | Three-Way Quick Sort |
|---|---|---|
| Number of Partitions | 2 (less than pivot, greater than pivot) | 3 (less than pivot, equal to pivot, greater than pivot) |
| Handling Duplicate Elements | Less efficient; duplicate elements may be compared and swapped multiple times | Highly efficient; duplicate elements are handled collectively |
| Time Complexity | Average O(n log n), worst O(n²) | Average O(n log n), worst O(n²) |
| Space complexity | O(log n) (recursion stack) | O(log n) (recursion stack) |
| Applicable scenarios | General-purpose sorting, low rate of duplicate elements | High rate of duplicate elements, such as color sorting and score segmentation |
Applicability Notes
The time and space complexity is the same as randomized quick sort.
The three-way quick sort algorithm uses a three-way partitioning strategy to divide the array, which is very effective for improving the quick sort process when handling arrays with a large number of duplicate elements. It adds logic for handling values equal to the partitioning element, gathering all values equal to the partitioning element together.
Process Diagram

We discuss the partiton process in three cases, where i represents the current index position during traversal:
(1) The current element being processed is e=V; element e is directly included in the blue interval, and i moves forward by one.

(2) The current element being processed e (3) The current element being processed e>v; swap e with the value at index gt-1, and the gt index moves forward by one. Finally, when i=gt, the traversal ends, and it is necessary to swap v with the value pointed to by index lt. This completes the sorting process, then the Source code package download:Download package runoob ; /**
public class QuickSort3Ways { // Core code---start // Recursively use quick sort to sort the range arr[l...r] private static void sort ( Comparable [ ] arr, int l, int r ) { if ( l = r ) { return ; } // Randomly select a value within the range arr[l...r] as the pivot point pivot swap ( arr, l, ( int ) ( Math . random ( ) ( r l 1 ) ) l ) ; Comparable v = arr [ l ] ; int lt = l ; // arr[l+1...lt] < v int gt = r 1 ; // arr[gt...r] > v int i = l 1 ; // arr[lt+1...i) == v while ( i . compareTo ( v ) arr, i, lt 1 ) ; i ++; lt ++; } else if ( arr [ i ] . compareTo ( v ) 0 ) { swap ( arr, i, gt 1 ) ; gt --; } else { // arr[i] == v i ++; } } swap ( arr, l, lt ) ; sort ( arr, l, lt 1 ) ; sort ( arr, gt, r ) ; } // Core code---end public static void sort ( Comparable [ ] arr ) { int n = arr. length ; sort ( arr, 0 , n 1 ) ; } private static void swap ( Object [ ] arr, int i, int j ) { Object t = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = t ; } // Test QuickSort3Ways public static void main ( String [ ] args ) { // The three-way quick sort algorithm is also an O(nlogn) complexity algorithm // Can easily process data on the order of 1 million within 1 second int N = 1000000 ; Integer [ ] arr = SortTestHelper. generateRandomArray ( N, 0 , 100000 ) ; sort ( arr ) ; SortTestHelper. printArray ( arr ) ; } } The ingenuity of the three-way sort algorithm lies in its use of three pointers to track different regions of the array, completing three classifications in a single traversal. Let us understand the partitioning process of the algorithm through a state diagram: Diagram Description: The algorithm maintains three pointers ( Below is an implementation of a standard three-way partition function, which we will analyze line by line: def three_way_partition ( arr , low , high ) : """
pivot = arr [ low ] lt = low i = low + 1 gt = high while i <= gt: if arr [ i ] < pivot: arr [ lt ] , arr [ i ] = arr [ i ] , arr [ lt ] lt + = 1 i + = 1 elif arr [ i ] pivot: arr [ i ] , arr [ gt ] = arr [ gt ] , arr [ i ] gt - = 1 else : i + = 1 return lt , gt Based on the partition function above, we can implement a complete three-way quick sort: def three_way_quicksort ( arr , low = 0 , high = None ) : """
if high is None : high = len ( arr ) 1 if low = high: return lt , gt = three_way_partition ( arr , low , high ) three_way_quicksort ( arr , low , lt - 1 ) three_way_quicksort ( arr , gt + 1 , high ) This is a classic application scenario of the three-way sort algorithm, also known as the "Dutch National Flag problem". def sort_colors ( colors ) : """
red_ptr = 0 white_ptr = 0 blue_ptr = len ( colors ) 1 while white_ptr <= blue_ptr: if colors [ white_ptr ] == 0 : colors [ red_ptr ] , colors [ white_ptr ] = colors [ white_ptr ] , colors [ red_ptr ] red_ptr + = 1 white_ptr + = 1 elif colors [ white_ptr ] == 1 : white_ptr + = 1 else : colors [ white_ptr ] , colors [ blue_ptr ] = colors [ blue_ptr ] , colors [ white_ptr ] blue_ptr - = 1 return colors test_colors = [ 2 , 0 , 2 , 1 , 1 , 0 , 1 , 2 , 0 , 1 , 0 , 2 ] print ( "Original color array:" , test_colors ) print ( "Sorted color array:" , sort_colors ( test_colors. copy ( ) ) ) Test Data Description: The array above represents color numbers (0=red, 1=white, 2=blue). After sorting, all 0s should be at the front, 1s in the middle, and 2s at the back. Suppose we need to segment based on student scores: less than 60 is failing, 60-80 is good, greater than 80 is excellent. def categorize_grades ( scores ) : """
if not scores: return scores low = 0 mid = 0 high = len ( scores ) 1 while mid <= high: if scores [ mid ] < 60 : scores [ low ] , scores [ mid ] = scores [ mid ] , scores [ low ] low + = 1 mid + = 1 elif scores [ mid ] <= 80 : mid + = 1 else : scores [ mid ] , scores [ high ] = scores [ high ] , scores [ mid ] high - = 1 mid = low high = len ( scores ) 1 while mid <= high: if scores [ mid ] <= 80 : mid + = 1 else : scores [ mid ] , scores [ high ] = scores [ high ] , scores [ mid ] high - = 1 return scores test_scores = [ 45 , 78 , 92 , 56 , 85 , 67 , 72 , 88 , 59 , 95 , 61 , 73 ] print ( "Original scores:" , test_scores ) print ( "Segmented scores:" , categorize_grades ( test_scores. copy ( ) ) ) print ( "Note: the front part<60, middle 60-80, back part >80" ) The time complexity analysis of the three-way sort algorithm can be expressed by the following formula: $$ T(n) = O(n) + T(k) + T(n - k - m) $$ Where: Best Case: Every partition divides the array evenly into three parts, with time complexity $O(n \log_3 n)$, which is actually still $O(n \log n)$. Worst Case: Every partition is extremely uneven, with time complexity $O(n^2)$. Average Case: For random data, the average time complexity is $O(n \log n)$. The algorithm is implemented recursively, and the recursion depth depends on the partitioning situation: Space usage can be reduced through tail recursion optimization or by using an iterative approach.

Java Example Code
QuickSort3Ways.java file code:
* Three-Way Quick Sort
*/
<
gt
)
{
if
(
arr
[
i
]<
0
)
{
swap
(
Core Idea and Working Principle of the Algorithm
Algorithm Partition State

lt, i, gt) dividing the array into four regions. As processing proceeds, the region to be processed gradually shrinks, eventually forming three clear partitions.The Roles of the Three Key Pointers
lt(less than) pointer: points to the end of the region less than the pivot valuei(current) pointer: the position of the element currently being examinedgt(greater than) pointer: points to the beginning of the region greater than the pivot value
Python Implementation
Basic Three-Way Partition Function
Example
Perform three-way partitioning on the range from low to high of array arr
Parameters:
arr: the array to be partitioned
low: the starting index of the partition
high: the ending index of the partition
Returns:
(lt, gt): the left and right boundaries of the region equal to the pivot value
"""Choose the pivot value (here the first element is chosen)
Initialize the three pointers
The right boundary of the region less than the pivot value (initially low)
The position of the element currently being examined
The left boundary of the region greater than the pivot value (initially high)
Main loop: continue while there are still unprocessed elements
Case 1: the current element is less than the pivot value
Swap it with the next element of the lt pointer, expanding the less-than region
Case 2: the current element is greater than the pivot value
Swap it with the element of the gt pointer, expanding the greater-than region
Note: i is not incremented here, because the swapped-over element has not yet been examined
Case 3: the current element is equal to the pivot value
Skip directly, expanding the equal-to region
Return the boundaries of the region equal to the pivot value
Complete Three-Way Quick Sort Implementation
Example
Main Function of Three-Way Quick Sort
Parameters:
arr: the array to be sorted
low: the starting index of sorting (default 0)
high: the ending index of sorting (default to the end of the array)
"""
Recursion termination condition: sub-array length less than or equal to 1
Perform three-way partitioning
Recursively sort the part less than the pivot value
Recursively sort the part greater than the pivot value
Note: the part equal to the pivot value is already in the correct position, no need to sort again
Practical Application Examples
Example 1: Color Sorting Problem
Example
Color sorting: arrange an array containing only 0 (red), 1 (white), 2 (blue) in order
Parameters:
colors: the color array, with elements 0, 1, 2
Returns:
The sorted color array
"""Initialize the three pointers
The end of the red region
The position currently being examined (also the end of the white region)
The beginning of the blue region
Red: swap into the red region
White: stay in the middle region
Blue: swap into the blue region
Note: white_ptr is not incremented here, because the swapped-over element has not yet been examined
Test Data
Example 2: Student Score Segmentation
Example
Divide the scores into three grades: failing (<60), good (60-80), excellent (>80)
Parameters:
scores: the score array
Returns:
The segmented score array
"""Using the three-way partitioning idea, with 60 and 80 as boundary points
First partition by 60: failing vs passing and above
First round: separate the failing scores (<60)
Second round: separate good and excellent from the passing-and-above part
At this point low points to the position of the first good score
Test Data
Algorithm Complexity Analysis
Time Complexity
Space complexity
More Code Examples