Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Three-Way Sort Algorithm

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 part of the array with values V is recursively sorted in the same way.

Java Example Code

Source code package download:Download

QuickSort3Ways.java file code:

package

runoob

;

/**
 * Three-Way Quick Sort
 */

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

<

gt

)

{

if

(

arr

[

i

]

.

compareTo

(

v

)

<

0

)

{

swap

(

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

)

;

   

}

}


Core Idea and Working Principle of the Algorithm

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.

Algorithm Partition State

Let us understand the partitioning process of the algorithm through a state diagram:

Diagram Description: The algorithm maintains three pointers (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

  1. lt(less than) pointer: points to the end of the region less than the pivot value
  2. i(current) pointer: the position of the element currently being examined
  3. gt(greater than) pointer: points to the beginning of the region greater than the pivot value

Python Implementation

Basic Three-Way Partition Function

Below is an implementation of a standard three-way partition function, which we will analyze line by line:

Example

def

three_way_partition

(

arr

,

low

,

high

)

:

   

"""
    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)

    pivot

=

arr

[

low

]

   

   

Initialize the three pointers

    lt

=

low      

The right boundary of the region less than the pivot value (initially low)

    i

=

low +

1

 

The position of the element currently being examined

    gt

=

high    

The left boundary of the region greater than the pivot value (initially high)

   

   

Main loop: continue while there are still unprocessed elements

   

while

i

<=

gt:

       

if

arr

[

i

]

<

pivot:

           

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

            arr

[

lt

]

,

arr

[

i

]

=

arr

[

i

]

,

arr

[

lt

]

            lt +

=

1

            i +

=

1

       

elif

arr

[

i

]

pivot:

           

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

            arr

[

i

]

,

arr

[

gt

]

=

arr

[

gt

]

,

arr

[

i

]

            gt -

=

1

           

Note: i is not incremented here, because the swapped-over element has not yet been examined

       

else

:

           

Case 3: the current element is equal to the pivot value

           

Skip directly, expanding the equal-to region

            i +

=

1

   

   

Return the boundaries of the region equal to the pivot value

   

return

lt

,

gt

Complete Three-Way Quick Sort Implementation

Based on the partition function above, we can implement a complete three-way quick sort:

Example

def

three_way_quicksort

(

arr

,

low

=

0

,

high

=

None

)

:

   

"""
    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)
    """

   

if

high

is

None

:

        high

=

len

(

arr

)

1

   

   

Recursion termination condition: sub-array length less than or equal to 1

   

if

low

=

high:

       

return

   

   

Perform three-way partitioning

    lt

,

gt

=

three_way_partition

(

arr

,

low

,

high

)

   

   

Recursively sort the part less than the pivot value

    three_way_quicksort

(

arr

,

low

,

lt -

1

)

   

   

Recursively sort the part greater than the pivot value

    three_way_quicksort

(

arr

,

gt +

1

,

high

)

   

   

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

This is a classic application scenario of the three-way sort algorithm, also known as the "Dutch National Flag problem".

Example

def

sort_colors

(

colors

)

:

   

"""
    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

    red_ptr

=

0

         

The end of the red region

    white_ptr

=

0

       

The position currently being examined (also the end of the white region)

    blue_ptr

=

len

(

colors

)

1

 

The beginning of the blue region

   

   

while

white_ptr

<=

blue_ptr:

       

if

colors

[

white_ptr

]

==

0

:

           

Red: swap into the red region

            colors

[

red_ptr

]

,

colors

[

white_ptr

]

=

colors

[

white_ptr

]

,

colors

[

red_ptr

]

            red_ptr +

=

1

            white_ptr +

=

1

       

elif

colors

[

white_ptr

]

==

1

:

           

White: stay in the middle region

            white_ptr +

=

1

       

else

:

           

Blue: swap into the blue region

            colors

[

white_ptr

]

,

colors

[

blue_ptr

]

=

colors

[

blue_ptr

]

,

colors

[

white_ptr

]

            blue_ptr -

=

1

           

Note: white_ptr is not incremented here, because the swapped-over element has not yet been examined

   

   

return

colors

Test Data

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.

Example 2: Student Score Segmentation

Suppose we need to segment based on student scores: less than 60 is failing, 60-80 is good, greater than 80 is excellent.

Example

def

categorize_grades

(

scores

)

:

   

"""
    Divide the scores into three grades: failing (<60), good (60-80), excellent (>80)
   
    Parameters:
        scores: the score array
       
    Returns:
        The segmented score array
    """

   

if

not

scores:

       

return

scores

   

   

Using the three-way partitioning idea, with 60 and 80 as boundary points

   

First partition by 60: failing vs passing and above

    low

=

0

    mid

=

0

    high

=

len

(

scores

)

1

   

   

First round: separate the failing scores (<60)

   

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

   

   

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

    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 Data

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"

)


Algorithm Complexity Analysis

Time Complexity

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)$.

Space complexity

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.


More Code Examples