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

Two-Way Quick Sort

Two-Way Quick Sort

The two-way quick sort algorithm is an improved version of randomized quick sort. The partition process uses two index values (i, j) to traverse the array, placing elements less than the pivot to the left of the position pointed to by index i, and placing >v elements greater than the pivot to the right of the position pointed to by index j,v represents the pivot value.

Applicability Notes

The time and space complexity is the same as randomized quick sort. For arrays with a large number of duplicate elements, using the randomized quick sort from the previous section is very inefficient, because after partition the sub-arrays of data greater than or less than the pivot become extremely unbalanced, and may even degrade into an algorithm with O(n*2) time complexity. For such cases, the two-way quick sort algorithm can be used.

Process Diagram

Use two index values (i, j) to traverse our sequence, placing <=v elements less than the pivot to the left of the position pointed to by index i, and placing >=v elements greater than the pivot to the right of the position pointed to by index j, balancing the left and right sub-arrays.

Java Example Code

Source code package download:Download

QuickSort2Ways.java file code:

package

runoob

;

/**
 * Two-Way Quick Sort
 */

public

class

QuickSort2Ways

{

   

// Core code---start

   

private

static

int

partition

(

Comparable

[

]

arr,

int

l,

int

r

)

{

       

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

]

;

       

// arr[l+1...i) <= v; arr(j...r] >= v

       

int

i

=

l

1

, j

=

r

;

       

while

(

true

)

{

           

while

(

i

<=

r

&&

arr

[

i

]

.

compareTo

(

v

)

<

0

)

i

++;

           

while

(

j

=

l

1

&&

arr

[

j

]

.

compareTo

(

v

)

0

)

                j

--;

           

if

(

i

j

)

               

break

;

            swap

(

arr, i, j

)

;

            i

++;

            j

--;

       

}

        swap

(

arr, l, j

)

;

       

return

j

;

   

}

   

// Core code---end

   

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

;

       

}

       

int

p

=

partition

(

arr, l, r

)

;

        sort

(

arr, l, p

1

)

;

        sort

(

arr, p

1

, r

)

;

   

}

   

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 QuickSort

   

public

static

void

main

(

String

[

]

args

)

{

       

// The two-way quick sort algorithm is also an O(nlogn) complexity algorithm

       

// Can easily process data on the order of 1 million within 1 second

       

// Quick Sort 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

)

;

   

}

}


Detailed Explanation of the Algorithm Principle

The core of two-way quick sort lies in its two-pointer partitioning method. Unlike single-way quick sort (which scans from only one end), it uses two pointers scanning toward the middle from the head and tail of the sub-array to be sorted, ensuring that equal elements are not all pushed to one side.

Core: Two-Way Partition Process

Suppose we want to sort the array arr with index from left to right the part to be sorted.

Choosing the Pivot Value: from the arr[left...right] Randomly select an element from it as the pivot value pivot. Randomization is used to avoid the worst case on sorted arrays.

Initializing Pointers:

  • i = left + 1: the pointer scanning from left to right, looking for the first Greater than or equal to pivot .
  • j = right: the pointer scanning from right to left, looking for the first Less than or equal to pivot .

Scanning and Swapping Loop:

  • while loop, with the condition that i <= j。
  • Inner while loop: let i keep moving right until arr[i] >= pivot。
  • Inner while loop: let j keep moving left until arr[j] <= pivot。
  • At this point,arr[i] is a "large" element that should not be in the left half,arr[j] is a "small" element that should not be in the right half.
  • If at this point i <= j, then swap arr[i] and arr[j], then i++, j--, and continue the outer loop.

Placing the Pivot and Returning the Split Point:

  • After the loop ends,i and j have crossed (j < i). At this point arr[left](i.e., the pivot value) needs to be placed in the correct position.
  • data to the child component via arr[left] The difference between arr[j] Swap. Because j the final resting position, the element it points to is the last one less than or equal to the pivot value .
  • Return j as the new split point. At this point,arr[left...j-1] <= pivot,arr[j+1...right] >= pivot, and arr[j] == pivot。

Recursive Sorting

Get the partition point p , then for the left sub-array arr[left...p-1] and the right sub-array arr[p+1...right] recursively perform the above process until the sub-array length is 1.


Code Implementation

Let us understand two-way quick sort concretely through a complete Java implementation.

1. Main Sorting Function

Example

public

class

TwoWayQuickSort

{

   

// Public sorting interface

   

public

static

void

sort

(

int

[

]

arr

)

{

       

if

(

arr

==

null

||

arr.

length

<

2

)

{

return

;

// Boundary condition handling: if the array is empty or has only one element, no sorting is needed

       

}

        quickSort

(

arr,

0

, arr.

length

1

)

;

// Call the recursive quick sort function

   

}

   

// Recursive quick sort function

   

private

static

void

quickSort

(

int

[

]

arr,

int

left,

int

right

)

{

       

// Recursion termination condition: when the left boundary is greater than or equal to the right boundary, the sub-array is already sorted or empty

       

if

(

left

=

right

)

{

           

return

;

       

}

       

       

// Key step: perform two-way partitioning and return the index of the partition point

       

int

p

=

partition

(

arr, left, right

)

;

       

       

// Recursively sort the left half (left, p-1)

        quickSort

(

arr, left, p

1

)

;

       

// Recursively sort the right half (p+1, right)

        quickSort

(

arr, p

1

, right

)

;

   

}

}

2. Core: Two-Way Partition Function

This is the core of the algorithm; please understand it carefully together with the flow chart and comments above.

Example

   

// Two-way partition function

   

private

static

int

partition

(

int

[

]

arr,

int

left,

int

right

)

{

       

// 1. Randomly select the pivot and swap it to the left position to avoid the worst case on sorted arrays

       

int

randomIndex

=

left

(

int

)

(

Math

.

random

(

)

(

right

left

1

)

)

;

        swap

(

arr, left, randomIndex

)

;

       

int

pivot

=

arr

[

left

]

;

// Pivot value

       

       

// 2. Initialize the two pointers

       

// i: scan from left to right, looking for elements >= pivot

       

// j: scan from right to left, looking for <= pivot elements

       

int

i

=

left

1

;

       

int

j

=

right

;

       

       

// 3. Main loop: while i and j have not yet crossed

       

while

(

i

<=

j

)

{

           

// 3.1 Move the left pointer i: find the first element >= pivot

           

// Note the boundary i <= right to prevent array out-of-bounds

           

while

(

i

<=

right

&&

arr

[

i

]

<

pivot

)

{

i

++;

           

}

           

// 3.2 Move the right pointer j: find the first <= pivot elements

           

// Note the boundary j >= left+1, because the left position is the pivot itself

           

while

(

j

=

left

1

&&

arr

[

j

]

pivot

)

{

                j

--;

           

}

           

           

// 3.3 Check pointer state

           

// If i > j, it means scanning is complete, the left and right partitions are ready, no swap needed

           

if

(

i

j

)

{

               

break

;

           

}

           

           

// 3.4 Swap arr[i] and arr[j]

           

// At this point arr[i] >= pivot, arr[j] <= pivot, swap them so that large and small elements each find their place

            swap

(

arr, i, j

)

;

           

// After swapping, move the pointers to continue scanning

            i

++;

            j

--;

       

}

       

       

// 4. Place the pivot value pivot at its final correct position j

       

// After the loop ends, j points to the last <= pivot elements

        swap

(

arr, left, j

)

;

       

       

// 5. Return the index j of the partition point

       

return

j

;

   

}

   

   

// Helper function: swap the positions of two elements in the array

   

private

static

void

swap

(

int

[

]

arr,

int

i,

int

j

)

{

       

int

temp

=

arr

[

i

]

;

        arr

[

i

]

=

arr

[

j

]

;

        arr

[

j

]

=

temp

;

   

}

}

3. Testing and Verification

Let us test our implementation with an array containing duplicate elements.

Example

public

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Test case 1: an array with a large number of duplicate elements

       

int

[

]

arr1

=

{

4

,

2

,

2

,

8

,

3

,

3

,

1

,

5

,

3

,

2

}

;

       

System

.

out

.

println

(

"Before sorting: "

Arrays

.

toString

(

arr1

)

)

;

        TwoWayQuickSort.

sort

(

arr1

)

;

       

System

.

out

.

println

(

"After sorting: "

Arrays

.

toString

(

arr1

)

)

;

       

       

// Test case 2: a randomly generated large array

       

int

[

]

arr2

=

new

int

[

20

]

;

       

Random

rand

=

new

Random

(

)

;

       

for

(

int

i

=

0

;

i

<

arr2.

length

;

i

++

)

{

            arr2

[

i

]

=

rand.

nextInt

(

50

)

;

// Generate random numbers from 0-49, very likely with duplicates

       

}

       

System

.

out

.

println

(

"\nBefore sorting the random array: "

Arrays

.

toString

(

arr2

)

)

;

        TwoWayQuickSort.

sort

(

arr2

)

;

       

System

.

out

.

println

(

"After sorting the random array: "

Arrays

.

toString

(

arr2

)

)

;

       

       

// Verify whether the sorting result is correct

       

for

(

int

i

=

1

;

i

<

arr2.

length

;

i

++

)

{

           

if

(

arr2

[

i

]

<

arr2

[

i

1

]

)

{

System

.

out

.

println

(

"Sorting error!"

)

;

               

return

;

           

}

       

}

       

System

.

out

.

println

(

"Sorting result verified successfully!"

)

;

   

}

}

Sample Test Data Output:

排序前: [4, 2, 2, 8, 3, 3, 1, 5, 3, 2]

排序后: [1, 2, 2, 2, 3, 3, 3, 4, 5, 8]



随机数组排序前: [17, 33, 12, 48, 8, 2, 41, ...]

随机数组排序后: [2, 8, 12, 17, 33, 33, 41, 48, ...]

排序结果验证通过!


Algorithm Analysis and Comparison

Time Complexity

  • Average Case: $O(n \log n)$. Two-way quick sort balances the distribution of duplicate elements, making the recursion tree relatively balanced.
  • Worst Case: $O(n^2)$. Although randomly choosing the pivot greatly reduces the probability, the worst case can still occur when every partition is extremely unbalanced (for example, when the pivot is each time the current minimum or maximum value).
  • Best Case: $O(n \log n)$. Every partition divides the array evenly.

Space complexity

  • Mainly the space occupied by the recursive call stack.
  • The average depth is $O(\log n)$, and the worst-case depth is $O(n)$.
  • Therefore,The average space complexity is $O(\log n)$, and the worst is $O(n)$。

Stability

Quick sort (including two-way quick sort) is not a stable sorting algorithm. Because during partitioning, the swapping of non-adjacent elements disrupts the original relative order of equal elements.

Comparison of Single-Way, Two-Way, and Three-Way Quick Sort

Feature Single-Way Quick Sort (Lomuto) Two-Way Quick Sort Three-Way Quick Sort
Partitioning Method Single pointer scanning from left to right Two pointers scanning from both ends toward the middle Three pointers, dividing the array into , =pivot, >pivot three parts
Handling Duplicate Elements Poor, may result in unbalanced partitions Good, it can distribute duplicate elements evenly Optimal, can handle all elements equal to the baseline value at once
Code complexity Simple Medium Slightly complex
Applicable scenarios For teaching, no/few duplicate elements General-purpose, especially suitable for scenarios that may have duplicate elements Scenarios with many duplicate elements

More Code Examples