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

Randomized Quick Sort

Randomized Quick Sort

Quick sort is one of the most classic sorting algorithms in computer science, renowned for its O(n log n) time complexity in the average case. However, when the input data is already sorted or nearly sorted, traditional quick sort degrades to O(n²) time complexity. Randomized quick sort elegantly solves this problem by introducing randomness.

Before diving into randomized quick sort, let's first review the core idea of traditional quick sort.

How quick sort works

Quick sort uses a divide-and-conquer strategy, whose basic steps are as follows:

  1. Choosing the Pivot Value: select an element from the array as the pivot
  2. Partition operation: rearrange the array so that all elements smaller than the pivot are placed before it, and all elements greater than the pivot are placed after it
  3. Recursive Sorting: recursively apply the same process to the subarrays on the left and right of the pivot

Problems with traditional quick sort

The performance of traditional quick sort depends heavily on the choice of pivot. The algorithm is most efficient when each chosen pivot splits the array roughly in half. However, performance degrades significantly in the following cases:

In these worst-case scenarios, the time complexity of quick sort degrades to O(n²), comparable to simple algorithms such as bubble sort.

Randomized quick sort avoids the worst case by introducing randomness, ensuring the algorithm maintains good average performance across all kinds of input.

The core improvement of randomized quick sort is very simple:Choose the pivot randomly, instead of always choosing the first, last, or middle element. This randomness makes the probability of hitting the worst case extremely low, thereby guaranteeing an expected time complexity of O(n log n).

**Basic idea of randomized quick sort:** through one pass of sorting, split the data to be sorted into two independent parts, where all data in one part is smaller than all data in the other part. Then apply quick sort to each of these two parts in the same way. The entire sorting process can proceed recursively, until the whole data becomes a sorted sequence.

Algorithm advantages

Feature Traditional Quick Sort Randomized Quick Sort
Worst-case time complexity O(n²) O(n²) (but with extremely low probability)
Average-case time complexity O(n log n) O(n log n)
Condition for the worst case to occur Specific input (such as a sorted array) Random selection happens to always pick an extreme value
Space complexity O(log n) (recursion stack) O(log n) (recursion stack)
Stability Unstable Unstable

Although the theoretical worst-case time complexity of randomized quick sort is still O(n²), in practical applications the probability of this worst case occurring is extremely low. For an array of n elements, the probability that random pivot selection leads to the worst case is about 1/n!, which is almost impossible in practice.

Process Diagram

Choose a pivot in an array, for example the 4 at the first position, then move 4 to its correct position so that all data in the subarray before it is less than 4 and all data in the subarray after it is greater than 4, then recurse gradually to complete the whole sort.

How to move the chosen pivot value to its correct position is the core of quick sort; we call it Partition.

The process is shown below, where i is the position of the element currently being traversed and compared:

This partition process is expressed in code as:

Example

    ...

private

static

int

partition

(

Comparable

[

]

arr,

int

l,

int

r

)

{

   

Comparable

v

=

arr

[

l

]

;

   

int

j

=

l

;

   

for

(

int

i

=

l

1

;

i

<=

r

;

i

++

)

       

if

(

arr

[

i

]

.

compareTo

(

v

)

<

0

)

{

j

++;

           

// swap the positions of array elements

            swap

(

arr, j, i

)

;

       

}

    swap

(

arr, l, j

)

;

   

return

j

;

}

   ...

If quick sort is applied to a nearly sorted array, the subarray sizes after each partition are extremely unbalanced, easily degrading into an O(n^2) time complexity algorithm. We need to optimize the code above by randomly choosing a pivot for comparison, which is called randomized quick sort. We only need to add the following line before the code above, randomly selecting one element in the array and swapping it with the pivot.

swap( arr, l , (int)(Math.random()*(r-l+1))+l );

Java Example Code

Source code package download:Download

QuickSort.java file code:

package

runoob

;

/**
 * Randomized quick sort
 */

public

class

QuickSort

{

   

// perform partition on the arr[l...r] portion

   

// return p such that arr[l...p-1] < arr[p] ; arr[p+1...r] > arr[p]

   

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...j] < v ; arr[j+1...i) > v

       

int

j

=

l

;

       

for

(

int

i

=

l

1

;

i

<=

r

;

i

++

)

           

if

(

arr

[

i

]

.

compareTo

(

v

)

<

0

)

{

j

++;

                swap

(

arr, j, i

)

;

           

}

        swap

(

arr, l, j

)

;

       

return

j

;

   

}

   

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

)

{

       

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

)

;

   

}

}


Implementation of randomized quick sort

Python Implementation

Example

import

random

def

randomized_quick_sort

(

arr

,

low

=

None

,

high

=

None

)

:

   

"""
    The main function of randomized quick sort
   
    Parameters:
    arr: the list to be sorted
    low: the starting index of the subarray (default 0)
    high: the ending index of the subarray (default len(arr)-1)
   
    Returns:
    The sorted list (sorts in place and also returns the sorted list)
    """

   

Set default parameters

   

if

low

is

None

:

        low

=

0

   

if

high

is

None

:

        high

=

len

(

arr

)

1

   

   

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

   

if

low

<

high:

       

Randomly choose a pivot and partition

        pivot_index

=

randomized_partition

(

arr

,

low

,

high

)

       

       

Recursively sort the left and right subarrays

        randomized_quick_sort

(

arr

,

low

,

pivot_index -

1

)

        randomized_quick_sort

(

arr

,

pivot_index +

1

,

high

)

   

   

return

arr

def

randomized_partition

(

arr

,

low

,

high

)

:

   

"""
    Randomized partition function
   
    Parameters:
    arr: the list to be partitioned
    low: the starting index of the subarray
    high: the ending index of the subarray
   
    Returns:
    The final position index of the pivot
    """

   

Randomly choose an index as the pivot position

    random_index

=

random

.

randint

(

low

,

high

)

   

   

Swap the randomly chosen element with the last element

    arr

[

random_index

]

,

arr

[

high

]

=

arr

[

high

]

,

arr

[

random_index

]

   

   

Use the last element (now the randomly chosen element) as the pivot

   

return

partition

(

arr

,

low

,

high

)

def

partition

(

arr

,

low

,

high

)

:

   

"""
    Partition function (same as quick sort)
   
    Parameters:
    arr: the list to be partitioned
    low: the starting index of the subarray
    high: the ending index of the subarray
   
    Returns:
    The final position index of the pivot
    """

    pivot

=

arr

[

high

]

 

Pivot

    i

=

low -

1

       

The boundary of the region with values less than the pivot

   

   

for

j

in

range

(

low

,

high

)

:

       

if

arr

[

j

]

<=

pivot:

            i +

=

1

           

Swap elements

            arr

[

i

]

,

arr

[

j

]

=

arr

[

j

]

,

arr

[

i

]

   

   

Place the pivot in its correct position

    arr

[

i +

1

]

,

arr

[

high

]

=

arr

[

high

]

,

arr

[

i +

1

]

   

return

i +

1

Test Data

test_data

=

[

3

,

6

,

8

,

10

,

1

,

2

,

1

]

print

(

"Original array:"

,

test_data

)

print

(

"Sorted array:"

,

randomized_quick_sort

(

test_data.

copy

(

)

)

)

Time complexity analysis

The time complexity of randomized quick sort can be expressed by the following formula:

[ T(n) = O(n) + T(k) + T(n - k - 1) ]

Where:

In the randomized version, the expected value of (k) is (n/2), so the expected time complexity is:

[ E[T(n)] = O(n \log n) ]


Variants and optimizations of randomized quick sort

1. Three-way quick sort

When the array contains many duplicate elements, traditional two-way quick sort is inefficient. Three-way quick sort divides the array into three parts: values less than the pivot, equal to the pivot, and greater than the pivot.

Example

def

randomized_three_way_quick_sort

(

arr

,

low

=

None

,

high

=

None

)

:

   

"""Three-way randomized quick sort"""

   

if

low

is

None

:

        low

=

0

   

if

high

is

None

:

        high

=

len

(

arr

)

1

   

   

if

low

<

high:

       

Choose the pivot randomly

        random_index

=

random

.

randint

(

low

,

high

)

        arr

[

random_index

]

,

arr

[

low

]

=

arr

[

low

]

,

arr

[

random_index

]

        pivot

=

arr

[

low

]

       

       

Three-way partition

        lt

=

low      

Boundary of the region less than the pivot

        gt

=

high    

Boundary of the region greater than the pivot

        i

=

low +

1

 

The element currently being examined

       

       

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

       

       

Recursively sort the parts less than and greater than the pivot

        randomized_three_way_quick_sort

(

arr

,

low

,

lt -

1

)

        randomized_three_way_quick_sort

(

arr

,

gt +

1

,

high

)

   

   

return

arr

Test data containing duplicate elements

test_data_with_duplicates

=

[

3

,

6

,

3

,

8

,

1

,

3

,

6

,

1

]

print

(

"Original array (with duplicates):"

,

test_data_with_duplicates

)

print

(

"After three-way quick sort:"

,

randomized_three_way_quick_sort

(

test_data_with_duplicates.

copy

(

)

)

)

2. Small-array optimization

For very small arrays (usually fewer than 10-20 elements), insertion sort can be more efficient than quick sort. We can combine the strengths of both algorithms:

Example

def

optimized_randomized_quick_sort

(

arr

,

low

=

None

,

high

=

None

,

threshold

=

10

)

:

   

"""Optimized randomized quick sort: use insertion sort for small arrays"""

   

if

low

is

None

:

        low

=

0

   

if

high

is

None

:

        high

=

len

(

arr

)

1

   

   

Use insertion sort for small arrays

   

if

high - low +

1

<=

threshold:

        insertion_sort

(

arr

,

low

,

high

)

       

return

arr

   

   

if

low

<

high:

        pivot_index

=

randomized_partition

(

arr

,

low

,

high

)

        optimized_randomized_quick_sort

(

arr

,

low

,

pivot_index -

1

,

threshold

)

        optimized_randomized_quick_sort

(

arr

,

pivot_index +

1

,

high

,

threshold

)

   

   

return

arr

def

insertion_sort

(

arr

,

low

,

high

)

:

   

"""Insertion sort, used for sorting small arrays"""

   

for

i

in

range

(

low +

1

,

high +

1

)

:

        key

=

arr

[

i

]

        j

=

i -

1

       

while

j

=

low

and

arr

[

j

]

key:

            arr

[

j +

1

]

=

arr

[

j

]

            j -

=

1

        arr

[

j +

1

]

=

key

Test the small-array optimization

small_test_data

=

[

9

,

3

,

7

,

1

,

5

,

2

,

8

,

4

,

6

]

print

(

"Original small array:"

,

small_test_data

)

print

(

"After optimized sort:"

,

optimized_randomized_quick_sort

(

small_test_data.

copy

(

)

,

threshold

=

5

)

)


Performance comparison and practical advice

Performance testing

Let's compare the performance of different sorting algorithms through practical tests:

Example

import

time

import

random

as

rand

def

performance_test

(

)

:

   

"""Performance test: compare the execution time of different sorting algorithms"""

    algorithms

=

{

       

"Randomized quick sort"

: randomized_quick_sort

,

       

"Three-way quick sort"

: randomized_three_way_quick_sort

,

       

"Optimized quick sort"

: optimized_randomized_quick_sort

,

   

}

   

   

Generate test data

    test_sizes

=

[

100

,

1000

,

10000

]

   

   

for

size

in

test_sizes:

       

print

(

f

"\nTest array size: {size}"

)

       

       

Generate different types of test data

        test_cases

=

{

           

"Random data"

:

[

rand.

randint

(

0

,

10000

)

for

_

in

range

(

size

)

]

,

           

"Sorted data"

:

list

(

range

(

size

)

)

,

           

"Reverse-ordered data"

:

list

(

range

(

size

,

0

,

1

)

)

,

           

"Data with many duplicates"

:

[

rand.

randint

(

0

,

10

)

for

_

in

range

(

size

)

]

,

       

}

       

       

for

case_name

,

test_data

in

test_cases.

items

(

)

:

           

print

(

f

"  {case_name}:"

)

           

           

for

algo_name

,

algo_func

in

algorithms.

items

(

)

:

                data_copy

=

test_data.

copy

(

)

                start_time

=

time

.

time

(

)

                algo_func

(

data_copy

)

                end_time

=

time

.

time

(

)

               

                execution_time

=

(

end_time - start_time

)

1000

 

Convert to milliseconds

               

print

(

f

"    {algo_name}: {execution_time:.2f} ms"

)

Run the performance test (note: for large arrays, this may take some time)

performance_test()


More Code Examples