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
Randomized Algorithms
Randomized algorithms in data structures and algorithms (DSA) are algorithms that use randomness in their computations to achieve a desired outcome. These algorithms introduce randomness to improve efficiency or simplify the algorithm design. By incorporating random choices into their processes, ran
2 min read
Random Variable
Random variable is a fundamental concept in statistics that bridges the gap between theoretical probability and real-world data. A Random variable in statistics is a function that assigns a real value to an outcome in the sample space of a random experiment. For example: if you roll a die, you can a
10 min read
Binomial Random Variables
In this post, we'll discuss Binomial Random Variables.Prerequisite : Random Variables A specific type of discrete random variable that counts how often a particular event occurs in a fixed number of tries or trials. For a variable to be a binomial random variable, ALL of the following conditions mus
8 min read
Randomized Algorithms | Set 0 (Mathematical Background)
Conditional Probability Conditional probability P(A | B) indicates the probability of even 'A' happening given that the even B happened.P(A|B) = \frac{P(A\cap B)}{P(B)} We can easily understand above formula using below diagram. Since B has already happened, the sample space reduces to B. So the pro
3 min read
Randomized Algorithms | Set 1 (Introduction and Analysis)
What is a Randomized Algorithm? An algorithm that uses random numbers to decide what to do next anywhere in its logic is called a Randomized Algorithm. For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). And in Karger's algorithm,
5 min read
Randomized Algorithms | Set 2 (Classification and Applications)
We strongly recommend to refer below post as a prerequisite of this. Randomized Algorithms | Set 1 (Introduction and Analysis) Classification Randomized algorithms are classified in two categories. Las Vegas: A Las Vegas algorithm were introduced by Laszlo Babai in 1979. A Las Vegas algorithm is an
13 min read
Randomized Algorithms | Set 3 (1/2 Approximate Median)
Time Complexity: We use a set provided by the STL in C++. In STL Set, insertion for each element takes O(log k). So for k insertions, time taken is O (k log k). Now replacing k with c log n =>O(c log n (log (clog n))) =>O (log n (log log n)) How is probability of error less than 2/n2? Algorithm make
2 min read
Easy problems on randomized algorithms
Write a function that generates one of 3 numbers according to given probabilities
You are given a function rand(a, b) which generates equiprobable random numbers between [a, b] inclusive. Generate 3 numbers x, y, z with probability P(x), P(y), P(z) such that P(x) + P(y) + P(z) = 1 using the given rand(a,b) function.The idea is to utilize the equiprobable feature of the rand(a,b)
5 min read
Generate 0 and 1 with 25% and 75% probability
Given a function rand50() that returns 0 or 1 with equal probability, write a function that returns 1 with 75% probability and 0 with 25% probability using rand50() only. Minimize the number of calls to the rand50() method. Also, the use of any other library function and floating-point arithmetic ar
13 min read
Implement rand3() using rand2()
Given a function rand2() that returns 0 or 1 with equal probability, implement rand3() using rand2() that returns 0, 1 or 2 with equal probability. Minimize the number of calls to rand2() method. Also, use of any other library function and floating point arithmetic are not allowed. The idea is to us
6 min read
Birthday Paradox
How many people must be there in a room to make the probability 100% that at-least two people in the room have same birthday? Answer: 367 (since there are 366 possible birthdays, including February 29). The above question was simple. Try the below question yourself. How many people must be there in
7 min read
Expectation or expected value of an array
Expectation or expected value of any group of numbers in probability is the long-run average value of repetitions of the experiment it represents. For example, the expected value in rolling a six-sided die is 3.5, because the average of all the numbers that come up in an extremely large number of ro
5 min read
Shuffle a deck of cards
Given a deck of cards, the task is to shuffle them. Asked in Amazon Interview Prerequisite : Shuffle a given array Algorithm: 1. First, fill the array with the values in order. 2. Go through the array and exchange each element with the randomly chosen element in the range from itself to the end. //
5 min read
Program to generate CAPTCHA and verify user
A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a test to determine whether the user is human or not.So, the task is to generate unique CAPTCHA every time and to tell whether the user is human or not by asking user to enter the same CAPTCHA as generated auto
6 min read
Find an index of maximum occurring element with equal probability
Given an array of integers, find the most occurring element of the array and return any one of its indexes randomly with equal probability.Examples: Input: arr[] = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9] Output: Element with maximum frequency present at index 6 OR Element with maximum frequen
8 min read
Randomized Binary Search Algorithm
We are given a sorted array A[] of n elements. We need to find if x is present in A or not.In binary search we always used middle element, here we will randomly pick one element in given range.In Binary Search we had middle = (start + end)/2 In Randomized binary search we do following Generate a ran
13 min read
Medium problems on randomized algorithms
Make a fair coin from a biased coin
You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with a 50% probability each. Your function should use only foo(), no other library method. Solution:Â We know fo
6 min read
Shuffle a given array using FisherâYates shuffle Algorithm
Given an array, write a program to generate a random permutation of array elements. This question is also asked as "shuffle a deck of cards" or "randomize a given array". Here shuffle means that every permutation of array element should be equally likely. Let the given array be arr[]. A simple solut
10 min read
Expected Number of Trials until Success
Consider the following famous puzzle. In a country, all families want a boy. They keep having babies till a boy is born. What is the expected ratio of boys and girls in the country? This puzzle can be easily solved if we know following interesting result in probability and expectation. If probabilit
6 min read
Strong Password Suggester Program
Given a password entered by the user, check its strength and suggest some password if it is not strong. Criteria for strong password is as follows : A password is strong if it has : At least 8 characters At least one special char At least one number At least one upper and one lower case char. Exampl
15 min read
QuickSort using Random Pivoting
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
15+ min read
Operations on Sparse Matrices
Given two sparse matrices (Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)), perform operations such as add, multiply or transpose of the matrices in their sparse form itself. The result should consist of three sparse matrices, one obtained by adding the two input matri
15+ min read
Estimating the value of Pi using Monte Carlo
Monte Carlo estimation Monte Carlo methods are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. One of the basic examples of getting started with the Monte Carlo algorithm is the estimation of Pi. Estimation of Pi The idea is to simulate ra
8 min read
Implement rand12() using rand6() in one line
Given a function, rand6() that returns random numbers from 1 to 6 with equal probability, implement the one-liner function rand12() using rand6() which returns random numbers from 1 to 12 with equal probability. The solution should minimize the number of calls to the rand6() method. Use of any other
7 min read
Hard problems on randomized algorithms
Generate integer from 1 to 7 with equal probability
Given a function foo() that returns integers from 1 to 5 with equal probability, write a function that returns integers from 1 to 7 with equal probability using foo() only. Minimize the number of calls to foo() method. Also, use of any other library function is not allowed and no floating point arit
6 min read
Implement random-0-6-Generator using the given random-0-1-Generator
Given a function random01Generator() that gives you randomly either 0 or 1, implement a function that utilizes this function and generate numbers between 0 and 6(both inclusive). All numbers should have same probabilities of occurrence. Examples: on multiple runs, it gives 3 2 3 6 0 Approach : The i
5 min read
Select a random number from stream, with O(1) space
Given a stream of numbers, generate a random number from the stream. You are allowed to use only O(1) space and the input is in the form of a stream, so can't store the previously seen numbers. So how do we generate a random number from the whole stream such that the probability of picking any numbe
10 min read
Random number generator in arbitrary probability distribution fashion
Given n numbers, each with some frequency of occurrence. Return a random number with probability proportional to its frequency of occurrence. Example: Let following be the given numbers. arr[] = {10, 30, 20, 40} Let following be the frequencies of given numbers. freq[] = {1, 6, 2, 1} The output shou
11 min read
Reservoir Sampling
Reservoir sampling is a family of randomized algorithms for randomly choosing k samples from a list of n items, where n is either a very large or unknown number. Typically n is large enough that the list doesn't fit into main memory. For example, a list of search queries in Google and Facebook.So we
11 min read
Linearity of Expectation
Prerequisite: Random Variable This post is about mathematical concepts like expectation, linearity of expectation. It covers one of the required topics to understand Randomized Algorithms. Let us consider the following simple problem. Problem: Given a fair dice with 6 faces, the dice is thrown n tim
4 min read
Introduction and implementation of Karger's algorithm for Minimum Cut
Given an undirected and unweighted graph, find the smallest cut (smallest number of edges that disconnects the graph into two components). The input graph may have parallel edges. For example consider the following example, the smallest cut has 2 edges. A Simple Solution use Max-Flow based s-t cut a
15+ min read
Select a Random Node from a Singly Linked List
Given a singly linked list, select a random node from the linked list (the probability of picking a node should be 1/N if there are N nodes in the list). You are given a random number generator.Below is a Simple Solution Count the number of nodes by traversing the list. Traverse the list again and s
14 min read
Select a Random Node from a tree with equal probability
Given a Binary Tree with children Nodes, Return a random Node with an equal Probability of selecting any Node in tree.Consider the given tree with root as 1. 10 / \ 20 30 / \ / \ 40 50 60 70 Examples: Input : getRandom(root); Output : A Random Node From Tree : 3 Input : getRandom(root); Output : A R
8 min read
Freivaldâs Algorithm to check if a matrix is product of two
Given three matrices A, B and C, find if C is a product of A and B. Examples: Input : A = 1 1 1 1 B = 1 1 1 1 C = 2 2 2 2 Output : Yes C = A x B Input : A = 1 1 1 1 1 1 1 1 1 B = 1 1 1 1 1 1 1 1 1 C = 3 3 3 3 1 2 3 3 3 Output : No A simple solution is to find product of A and B and then check if pro
12 min read
Random Acyclic Maze Generator with given Entry and Exit point
Given two integers N and M, the task is to generate any N * M sized maze containing only 0 (representing a wall) and 1 (representing an empty space where one can move) with the entry point as P0 and exit point P1 and there is only one path between any two movable positions. Note: P0 and P1 will be m
15+ min read