QuickSort using Random Pivoting
Last Updated :
14 Sep, 2023
In this article, we will discuss how to implement QuickSort using random pivoting. In QuickSort we first partition the array in place such that all elements to the left of the pivot element are smaller, while all elements to the right of the pivot are greater than the pivot. Then we recursively call the same procedure for left and right subarrays.
Unlike merge sort, we don't need to merge the two sorted arrays. Thus Quicksort requires lesser auxiliary space than Merge Sort, which is why it is often preferred to Merge Sort. Using a randomly generated pivot we can further improve the time complexity of QuickSort.
We have discussed at two popular methods for partitioning the arrays-Hoare's vs Lomuto partition scheme
It is advised that the reader has read that article or knows how to implement the QuickSort using either of the two partition schemes.
Algorithm for random pivoting using Lomuto Partitioning
partition(arr[], lo, hi)
pivot = arr[hi]
i = lo // place for swapping
for j := lo to hi – 1 do
if arr[j] <= pivot then
swap arr[i] with arr[j]
i = i + 1
swap arr[i] with arr[hi]
return i
partition_r(arr[], lo, hi)
r = Random Number from lo to hi
Swap arr[r] and arr[hi]
return partition(arr, lo, hi)
quicksort(arr[], lo, hi)
if lo < hi
p = partition_r(arr, lo, hi)
quicksort(arr, lo , p-1)
quicksort(arr, p+1, hi)
Implementation using Lomuto Partitioning:
C++
// C++ implementation QuickSort
// using Lomuto's partition Scheme.
#include <cstdlib>
#include <time.h>
#include <iostream>
using namespace std;
// This function takes last element
// as pivot, places
// the pivot element at its correct
// position in sorted array, and
// places all smaller (smaller than pivot)
// to left of pivot and all greater
// elements to right of pivot
int partition(int arr[], int low, int high)
{
// pivot
int pivot = arr[high];
// Index of smaller element
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller
// than or equal to pivot
if (arr[j] <= pivot) {
// increment index of
// smaller element
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (i + 1);
}
// Generates Random Pivot, swaps pivot with
// end element and calls the partition function
int partition_r(int arr[], int low, int high)
{
// Generate a random number in between
// low .. high
srand(time(NULL));
int random = low + rand() % (high - low);
// Swap A[random] with A[high]
swap(arr[random], arr[high]);
return partition(arr, low, high);
}
/* The main function that implements
QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high) {
/* pi is partitioning index,
arr[p] is now
at right place */
int pi = partition_r(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout<<arr[i]<<" ";
}
// Driver Code
int main()
{
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int partition(int arr[], int low, int high)
{
int pivot = arr[low];
int i = low - 1, j = high + 1;
while (1) {
do {
i++;
} while (arr[i] < pivot);
do {
j--;
} while (arr[j] > pivot);
if (i >= j)
return j;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int partition_r(int arr[], int low, int high)
{
srand(time(0));
int random = low + rand() % (high - low);
int temp = arr[random];
arr[random] = arr[low];
arr[low] = temp;
return partition(arr, low, high);
}
void quickSort(int arr[], int low, int high)
{
if (low < high) {
int pi = partition_r(arr, low, high);
quickSort(arr, low, pi);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Java
// Java program to illustrate
// Randomised Quick Sort
import java.util.*;
class RandomizedQsort
{
// This Function helps in calculating
// random numbers between low(inclusive)
// and high(inclusive)
static void random(int arr[],int low,int high)
{
Random rand= new Random();
int pivot = rand.nextInt(high-low)+low;
int temp1=arr[pivot];
arr[pivot]=arr[high];
arr[high]=temp1;
}
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
static int partition(int arr[], int low, int high)
{
// pivot is chosen randomly
random(arr,low,high);
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j = low; j < high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] < pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void sort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver Code
public static void main(String args[])
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = arr.length;
sort(arr, 0, n-1);
System.out.println("Sorted array");
printArray(arr);
}
}
// This code is contributed by Ritika Gupta.
Python3
# Python implementation QuickSort using
# Lomuto's partition Scheme.
import random
'''
The function which implements QuickSort.
arr :- array to be sorted.
start :- starting index of the array.
stop :- ending index of the array.
'''
def quicksort(arr, start , stop):
if(start < stop):
# pivotindex is the index where
# the pivot lies in the array
pivotindex = partitionrand(arr,\
start, stop)
# At this stage the array is
# partially sorted around the pivot.
# Separately sorting the
# left half of the array and the
# right half of the array.
quicksort(arr , start , pivotindex-1)
quicksort(arr, pivotindex + 1, stop)
# This function generates random pivot,
# swaps the first element with the pivot
# and calls the partition function.
def partitionrand(arr , start, stop):
# Generating a random number between the
# starting index of the array and the
# ending index of the array.
randpivot = random.randrange(start, stop)
# Swapping the starting element of
# the array and the pivot
arr[start], arr[randpivot] = \
arr[randpivot], arr[start]
return partition(arr, start, stop)
'''
This function takes the first element as pivot,
places the pivot element at the correct position
in the sorted array. All the elements are re-arranged
according to the pivot, the elements smaller than the
pivot is places on the left and the elements
greater than the pivot is placed to the right of pivot.
'''
def partition(arr,start,stop):
pivot = start # pivot
# a variable to memorize where the
i = start + 1
# partition in the array starts from.
for j in range(start + 1, stop + 1):
# if the current element is smaller
# or equal to pivot, shift it to the
# left side of the partition.
if arr[j] <= arr[pivot]:
arr[i] , arr[j] = arr[j] , arr[i]
i = i + 1
arr[pivot] , arr[i - 1] =\
arr[i - 1] , arr[pivot]
pivot = i - 1
return (pivot)
# Driver Code
if __name__ == "__main__":
array = [10, 7, 8, 9, 1, 5]
quicksort(array, 0, len(array) - 1)
print(array)
# This code is contributed by soumyasaurav
C#
// C# program to illustrate
// Randomised Quick sort
using System;
class RandomizedQsort
{
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
static int partition(int[] arr, int low, int high)
{
// pivot is chosen randomly
random(arr, low, high);
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j = low; j < high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] < pivot)
{
i++;
// swap arr[i] and arr[j]
int tempp = arr[i];
arr[i] = arr[j];
arr[j] = tempp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int tempp2 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = tempp2;
return i + 1;
}
// This Function helps in calculating
// random numbers between low(inclusive)
// and high(inclusive)
static int random(int[] arr, int low, int high)
{
Random rand = new Random();
int pivot = rand.Next() % (high - low) + low;
int tempp1 = arr[pivot];
arr[pivot] = arr[high];
arr[high] = tempp1;
return partition(arr, low, high);
}
/* The main function that implements Quicksort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void sort(int[] arr, int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi - 1);
sort(arr, pi + 1, high);
}
}
/* A utility function to print array of size n */
static void printArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver Code
static public void Main ()
{
int[] arr = {10, 7, 8, 9, 1, 5};
int n = arr.Length;
sort(arr, 0, n-1);
Console.WriteLine("sorted array");
printArray(arr);
}
}
// This code is contributed by shubhamsingh10
JavaScript
// JavaScript implementation QuickSort using
// Lomuto's partition Scheme.
/*
The function which implements QuickSort.
arr :- array to be sorted.
start :- starting index of the array.
stop :- ending index of the array.
*/
function quicksort(arr, start, stop) {
if (start < stop) {
// pivotindex is the index where
// the pivot lies in the array
let pivotindex = partitionrand(arr, start, stop);
// At this stage the array is
// partially sorted around the pivot.
// Separately sorting the
// left half of the array and the
// right half of the array.
quicksort(arr, start, pivotindex - 1);
quicksort(arr, pivotindex + 1, stop);
}
}
// This function generates random pivot,
// swaps the first element with the pivot
// and calls the partition function.
function partitionrand(arr, start, stop) {
// Generating a random number between the
// starting index of the array and the
// ending index of the array.
let randpivot = Math.floor(Math.random() * (stop - start + 1)) + start;
// Swapping the starting element of
// the array and the pivot
[arr[start], arr[randpivot]] = [arr[randpivot], arr[start]];
return partition(arr, start, stop);
}
/*
This function takes the first element as pivot,
places the pivot element at the correct position
in the sorted array. All the elements are re-arranged
according to the pivot, the elements smaller than the
pivot is places on the left and the elements
greater than the pivot is placed to the right of pivot.
*/
function partition(arr, start, stop) {
let pivot = start; // pivot
// a variable to memorize where the
let i = start + 1;
// partition in the array starts from.
for (let j = start + 1; j <= stop; j++) {
// if the current element is smaller
// or equal to pivot, shift it to the
// left side of the partition.
if (arr[j] <= arr[pivot]) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
}
}
[arr[pivot], arr[i - 1]] = [arr[i - 1], arr[pivot]];
pivot = i - 1;
return pivot;
}
// Driver Code
let array = [10, 7, 8, 9, 1, 5];
quicksort(array, 0, array.length - 1);
console.log(array);
OutputSorted array:
1 5 7 8 9 10
Time Complexity: O(N*N)
Auxiliary Space: O(N) // due to recursive call stack
Algorithm for random pivoting using Hoare Partitioning
partition(arr[], lo, hi)
pivot = arr[lo]
i = lo - 1 // Initialize left index
j = hi + 1 // Initialize right index
while(True)
// Find a value in left side greater than pivot
do
i = i + 1
while arr[i] < pivot
// Find a value in right side smaller than pivot
do
j = j - 1
while arr[j] > pivot
if i >= j then
return j
else
swap arr[i] with arr[j]
end while
partition_r(arr[], lo, hi)
r = Random number from lo to hi
Swap arr[r] and arr[lo]
return partition(arr, lo, hi)
quicksort(arr[], lo, hi)
if lo < hi
p = partition_r(arr, lo, hi)
quicksort(arr, lo, p)
quicksort(arr, p+1, hi)
Implementation using Hoare's Partitioning:
C++
// C++ implementation of QuickSort
// using Hoare's partition scheme
#include <cstdlib>
#include <iostream>
using namespace std;
// This function takes last element as
// pivot, places the pivot element at
// its correct position in sorted
// array, and places all smaller
// (smaller than pivot) to left of pivot
// and all greater elements to right
int partition(int arr[], int low, int high)
{
int pivot = arr[low];
int i = low - 1, j = high + 1;
while (true) {
// Find leftmost element greater than
// or equal to pivot
do {
i++;
} while (arr[i] < pivot);
// Find rightmost element smaller than
// or equal to pivot
do {
j--;
} while (arr[j] > pivot);
// If two pointers met
if (i >= j)
return j;
swap(arr[i], arr[j]);
}
}
// Generates Random Pivot, swaps pivot with
// end element and calls the partition function
// In Hoare partition the low element is selected
// as first pivot
int partition_r(int arr[], int low, int high)
{
// Generate a random number in between
// low .. high
srand(time(NULL));
int random = low + rand() % (high - low);
// Swap A[random] with A[high]
swap(arr[random], arr[low]);
return partition(arr, low, high);
}
// The main function that implements QuickSort
// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
void quickSort(int arr[], int low, int high)
{
if (low < high) {
// pi is partitioning index,
// arr[p] is now at right place
int pi = partition_r(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi);
quickSort(arr, pi + 1, high);
}
}
// Function to print an array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver Code
int main()
{
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Java
/*
JAVA implementation of Randomize QuickSort
using Hoare's Partition
*/
import java.util.*;
class GFG
{
// swap function
static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*
// partition function
This function takes array, low and high index,
swaps low with random index between low and high
then places all elements less than pivot in the left
of pivot and all elements greater than pivot to the
right of pivot
*/
static int partition(int[] arr, int low, int high)
{
// rIndex gives the random index between low and
// high (both inclusive)
int rIndex = (low) + (int)(Math.random() * (high - low + 1));
swap(arr, low, rIndex); // swap low with random index
int pivot = arr[low];
int i = low - 1, j = high + 1;
while (true) {
// increase i while elements are less than pivot
do {
i++;
} while (arr[i] < pivot);
// decrease j while elements are greater than pivot
do {
j--;
} while (arr[j] > pivot);
if (i >= j) // when both pointers meet
// that means elements are at their
// correct place for now
return j;
swap(arr, i, j);
// swap i and j, since both are not at their
// correct index
}
}
// recursive quick sort function
static void quickSort(int[] arr, int low, int high)
{
if (low < high) {
// find partition index
int p = partition(arr, low, high);
// sort before and after the pivot
quickSort(arr, low, p);
quickSort(arr, p + 1, high);
}
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 10, 7, 8, 9, 1, 5 };
quickSort(arr, 0, arr.length - 1);
System.out.println("Sorted array : ");
System.out.print(Arrays.toString(arr));
}
}
// This code is contributed by Anubhav Singh (singhanubhav)
Python3
# Python implementation QuickSort using
# Hoare's partition Scheme.
import random
'''
The function which implements randomised
QuickSort, using Haore's partition scheme.
arr :- array to be sorted.
start :- starting index of the array.
stop :- ending index of the array.
'''
def quicksort(arr, start, stop):
if(start < stop):
# pivotindex is the index where
# the pivot lies in the array
pivotindex = partitionrand(arr,\
start, stop)
# At this stage the array is
# partially sorted around the pivot.
# separately sorting the left half of
# the array and the right
# half of the array.
quicksort(arr , start , pivotindex)
quicksort(arr, pivotindex + 1, stop)
# This function generates random pivot,
# swaps the first element with the pivot
# and calls the partition function.
def partitionrand(arr , start, stop):
# Generating a random number between
# the starting index of the array and
# the ending index of the array.
randpivot = random.randrange(start, stop)
# Swapping the starting element of
# the array and the pivot
arr[start], arr[randpivot] =\
arr[randpivot], arr[start]
return partition(arr, start, stop)
'''
This function takes the first element
as pivot, places the pivot element at
the correct position in the sorted array.
All the elements are re-arranged according
to the pivot, the elements smaller than
the pivot is places on the left and
the elements greater than the pivot is
placed to the right of pivot.
'''
def partition(arr,start,stop):
pivot = start # pivot
i = start - 1
j = stop + 1
while True:
while True:
i = i + 1
if arr[i] >= arr[pivot]:
break
while True:
j = j - 1
if arr[j] <= arr[pivot]:
break
if i >= j:
return j
arr[i] , arr[j] = arr[j] , arr[i]
# Driver Code
if __name__ == "__main__":
array = [10, 7, 8, 9, 1, 5]
quicksort(array, 0, len(array) - 1)
print(array)
# This code is contributed by soumyasaurav
C#
// C# implementation of QuickSort
// using Hoare's partition scheme
using System;
public class GFG {
// Driver Code
public static void Main()
{
int[] arr = { 10, 7, 8, 9, 1, 5 };
int n = arr.Length;
quickSort(arr, 0, n - 1);
Console.WriteLine("Sorted array: ");
printArray(arr, n);
}
// This function takes last element as
// pivot, places the pivot element at
// its correct position in sorted
// array, and places all smaller
// (smaller than pivot) to left of pivot
// and all greater elements to right
public static int partition(int[] arr, int low,
int high)
{
int pivot = arr[low];
int i = low - 1, j = high + 1;
// Find leftmost element greater than
// or equal to pivot
while (true) {
do {
i++;
} while (arr[i] < pivot);
// Find rightmost element smaller than
// or equal to pivot
do {
j--;
} while (arr[j] > pivot);
// If two pointers met
if (i >= j)
return j;
swap(arr, i, j);
}
}
// Generates Random Pivot, swaps pivot with
// end element and calls the partition function
// In Hoare partition the low element is selected
// as first pivot
public static int partition_r(int[] arr, int low,
int high)
{
// Generate a random number in between
// low .. high
Random rnd = new Random();
int random = low + rnd.Next(high - low);
// Swap A[random] with A[high]
swap(arr, random, low);
return partition(arr, low, high);
}
// The main function that implements QuickSort
// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
public static void quickSort(int[] arr, int low,
int high)
{
if (low < high) {
// pi is partitioning index,
// arr[p] is now at right place
int pi = partition_r(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi);
quickSort(arr, pi + 1, high);
}
}
// Function to print an array
public static void printArray(int[] arr, int n)
{
for (int i = 0; i < n; i++)
Console.Write("{0} ", arr[i]);
Console.Write("\n");
}
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
JavaScript
// javascript implementation of QuickSort
// using Hoare's partition scheme
// This function takes last element as
// pivot, places the pivot element at
// its correct position in sorted
// array, and places all smaller
// (smaller than pivot) to left of pivot
// and all greater elements to right
function partition(arr, low, high)
{
let pivot = arr[low];
let i = low - 1, j = high + 1;
while (true) {
// Find leftmost element greater than
// or equal to pivot
do {
i++;
} while (arr[i] < pivot);
// Find rightmost element smaller than
// or equal to pivot
do {
j--;
} while (arr[j] > pivot);
// If two pointers met
if (i >= j)
return j;
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Generates Random Pivot, swaps pivot with
// end element and calls the partition function
// In Hoare partition the low element is selected
// as first pivot
function partition_r(arr, low, high)
{
// Generate a random number in between
// low .. high
let random = low + Math.random() * (high - low);
// Swap A[random] with A[high]
let temp = arr[random];
arr[random] = arr[low];
arr[low] = arr[random];
return partition(arr, low, high);
}
// The main function that implements QuickSort
// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
function quickSort(arr, low, high)
{
if (low < high) {
// pi is partitioning index,
// arr[p] is now at right place
let pi = partition_r(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi);
quickSort(arr, pi + 1, high);
}
}
// Function to print an array
function printArray(arr, n)
{
for (let i = 0; i < n; i++)
process.stdout.write(arr[i] + " ");
}
// Driver Code
let arr = [ 10, 7, 8, 9, 1, 5 ];
let n = arr.length
quickSort(arr, 0, n - 1);
console.log("Sorted array: ");
printArray(arr, n);
// The code is contributed by Nidhi goel.
OutputSorted array:
1 5 7 8 9 10
Time Complexity: O(N*N)
Auxiliary Space: O(N) // due to recursive call stack
Implementation using generateRandomPivot function :
Here is an implementation without using Hoare's and Lomuto partition scheme
Implementation of QuickSort using random pivoting without partitioning:
C++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to generate a random pivot index
int generateRandomPivot(int low, int high) {
srand(time(NULL));
return low + rand() % (high - low + 1);
}
// Function to perform QuickSort
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivotIndex = generateRandomPivot(low, high);
int pivotValue = arr[pivotIndex];
// Swap the pivot element with the last element
swap(&arr[pivotIndex], &arr[high]);
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivotValue) {
i++;
swap(&arr[i], &arr[j]);
}
}
// Swap the pivot element back to its final position
swap(&arr[i+1], &arr[high]);
// Recursively sort the left and right subarrays
quickSort(arr, low, i);
quickSort(arr, i+2, high);
}
}
int main() {
int arr[] = {5, 2, 7, 3, 1, 6, 4, 8};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Original array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
quickSort(arr, 0, n-1);
cout << "\nSorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Java
import java.util.Random;
public class QuickSort {
// Function to swap two elements in the array
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Function to generate a random pivot index
static int generateRandomPivot(int low, int high) {
Random random = new Random();
return random.nextInt(high - low + 1) + low;
}
// Function to perform QuickSort
static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = generateRandomPivot(low, high);
int pivotValue = arr[pivotIndex];
// Swap the pivot element with the last element
swap(arr, pivotIndex, high);
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivotValue) {
i++;
swap(arr, i, j);
}
}
// Swap the pivot element back to its final position
swap(arr, i + 1, high);
// Recursively sort the left and right subarrays
quickSort(arr, low, i);
quickSort(arr, i + 2, high);
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {5, 2, 7, 3, 1, 6, 4, 8};
int n = arr.length;
System.out.print("Original array: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
quickSort(arr, 0, n - 1);
System.out.print("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
Python3
import random
# Function to swap two elements
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
# Function to generate a random pivot index
def generateRandomPivot(low, high):
return random.randint(low, high)
# Function to perform QuickSort
def quickSort(arr, low, high):
if low < high:
pivotIndex = generateRandomPivot(low, high)
pivotValue = arr[pivotIndex]
# Swap the pivot element with the last element
swap(arr, pivotIndex, high)
i = low - 1
for j in range(low, high):
if arr[j] < pivotValue:
i += 1
swap(arr, i, j)
# Swap the pivot element back to its final position
swap(arr, i+1, high)
# Recursively sort the left and right subarrays
quickSort(arr, low, i)
quickSort(arr, i+2, high)
# Driver code
arr = [5, 2, 7, 3, 1, 6, 4, 8]
n = len(arr)
print("Original array:", arr)
quickSort(arr, 0, n-1)
print("Sorted array:", arr)
C#
using System;
class Program {
// Function to swap two elements
static void Swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Function to generate a random pivot index
static int GenerateRandomPivot(int low, int high) {
Random random = new Random();
return low + random.Next(high - low + 1);
}
// Function to perform QuickSort
static void QuickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = GenerateRandomPivot(low, high);
int pivotValue = arr[pivotIndex];
// Swap the pivot element with the last element
Swap(arr, pivotIndex, high);
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivotValue) {
i++;
Swap(arr, i, j);
}
}
// Swap the pivot element back to its final position
Swap(arr, i+1, high);
// Recursively sort the left and right subarrays
QuickSort(arr, low, i);
QuickSort(arr, i+2, high);
}
}
static void Main() {
int[] arr = {5, 2, 7, 3, 1, 6, 4, 8};
int n = arr.Length;
Console.Write("Original array: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
QuickSort(arr, 0, n-1);
Console.Write("\nSorted array: ");
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
}
}
JavaScript
// Function to swap two elements
function swap(arr, i, j) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Function to generate a random pivot index
function generateRandomPivot(low, high) {
return Math.floor(Math.random() * (high - low + 1)) + low;
}
// Function to perform QuickSort
function quickSort(arr, low, high) {
if (low < high) {
let pivotIndex = generateRandomPivot(low, high);
let pivotValue = arr[pivotIndex];
// Swap the pivot element with the last element
swap(arr, pivotIndex, high);
let i = low - 1;
for (let j = low; j < high; j++) {
if (arr[j] < pivotValue) {
i++;
swap(arr, i, j);
}
}
// Swap the pivot element back to its final position
swap(arr, i + 1, high);
// Recursively sort the left and right subarrays
quickSort(arr, low, i);
quickSort(arr, i + 2, high);
}
}
// Driver code
let arr = [5, 2, 7, 3, 1, 6, 4, 8];
let n = arr.length;
console.log("Original array: [" + arr.join(", ") + "]");
quickSort(arr, 0, n - 1);
console.log("Sorted array: [" + arr.join(", ") + "]");
OutputOriginal array: 5 2 7 3 1 6 4 8
Sorted array: 1 2 3 4 5 6 7 8
Analysis of Randomized Quick Sort
Notes
- Using random pivoting we improve the expected or average time complexity to O (N log N). The Worst-Case complexity is still O ( N^2 ).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem