Question

In: Computer Science

Write an implementation of quicksort where the pivot is selected randomly.

Write an implementation of quicksort where the pivot is selected randomly.

Solutions

Expert Solution

ANSWER :

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 that 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 auxillary 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 partioning the arrays-Hoare’s vs Lomuto partition scheme

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 that 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 auxillary 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 partioning 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, p-1, hi)
        quicksort(arr, p+1, hi)
 
partition(arr[], lo, hi)
   pivot = arr[lo]
   i = lo - 1  // Initialize left index
   j = hi + 1  // Initialize right index

   // Find a value in left side greater
   // than pivot
   do
i = i + 1
   while arr[i]  pivot

   if i >= j then 
      return j

   swap arr[i] with arr[j]
   
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, p, hi)
        quicksort(arr, p+1, hi)
        

CPP implementation of the Algorithms ; Lomuto (C++)

/* C++ implementation QuickSort using Lomuto'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

  of pivot */

int partition(int arr[], int low, int high)

{

    int pivot = arr[high]; // pivot

    int i = (low - 1); // Index of smaller element

for (int j = low; j <= high - 1; j++) {

        // If current element is smaller than or

        // equal to pivot

        if (arr[j] <= pivot) {

            i++; // increment index of smaller element

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

        printf("%d ", arr[i]);

    printf("

");

}

// Driver program to test above functions

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

printArray(arr, n);

    return 0;

}

Hoare (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

   of pivot */

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

}

// Driver program to test above functions

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

    printArray(arr, n);

    return 0;

}


Related Solutions

If we change the randomized QUICKSORT algorithm so that it repeatedly randomly selects a pivot and...
If we change the randomized QUICKSORT algorithm so that it repeatedly randomly selects a pivot and runs PARTITION until it finds a good pivot, and suppose we keep track of the pivots used so far so we never use one twice for the same array, what is the worst case cost of the algorithm? Give a recurrence for this and its asymptotic solution (you can use the master method.)
in C++, Modify the quicksort algorithm such that it uses the last item as the pivot...
in C++, Modify the quicksort algorithm such that it uses the last item as the pivot instead of the 1st. Also, sort in descending order, instead of ascending order. NOTE: Do not move the last element into the first element of the array. You must treat the algorithm as if the pivot is actually sitting in the last location of the array. After it has been sorted in descending order, go through all the items in the array and make...
(do not need to code) Consider QuickSort on the array A[1:n] andassume that the pivot...
Consider QuickSort on the array A[1:n] and assume that the pivot element x (used to split the array A[lo:hi] into two portions such that all elements in the left portion A[lo:m] are =< x and all elements in the right portion A[m:hi] are >=x) is the first element of the array to be split (i. e., A[lo]).Construct an infinite sequence of numbers for n and construct an assignment of the numbers 1...n to the n array elements that causes QuickSort,...
Quicksort (underline the pivot at each step) 19, 22, 8, 90, 13
Quicksort (underline the pivot at each step) 19, 22, 8, 90, 13
. Consider QuickSort on the array A[1:n] and assume that the pivot element x (used to...
. Consider QuickSort on the array A[1:n] and assume that the pivot element x (used to split the array A[lo:hi] into two portions such that all elements in the left portion A[lo:m] are ≤x and all elements in the right portion A[m:hi] are ≥x) is the second element of the array to be split (i. e., A[lo+1]). For a specific value of n at least 13 (your choice), construct an assignment of the numbers 1...n to the n array elements...
What is the reason to choose a random pivot element in Randomized Quicksort? How can using...
What is the reason to choose a random pivot element in Randomized Quicksort? How can using randomization in this way possibly help?
implement c++ Quicksort using median of 3 as pivot. this also pass comparator as a function...
implement c++ Quicksort using median of 3 as pivot. this also pass comparator as a function param so it can sort vector in increasing or decreasing order based on the comparator passed. the test code uses std::less comparator. #ifndef QSORT_H #define QSORT_H #include #include using namespace std; template T median_of_three(T& a, T& b, T& c, TComparator comparator) { } template size_t partition(vector& vec, TComparator& comparator, size_t low, size_t high) { // TODO: implement. } template void QuickSort(vector& vec, TComparator comparator,size_t...
Consider QuickSort on the array A[1:n] and assume that the pivot element x (used to split...
Consider QuickSort on the array A[1:n] and assume that the pivot element x (used to split the array A[lo:hi] into two portions such that all elements in the left portion A[lo:m] are ≤x and all elements in the right portion A[m:hi] are ≥x) is the second element of the array to be split (i. e., A[lo+1]). For a specific value of n at least 13 (your choice), construct an assignment of the numbers 1...n to the n array elements that...
At a home-and-garden show, randomly selected visitors were asked where they lived and where they normally...
At a home-and-garden show, randomly selected visitors were asked where they lived and where they normally shopped for their garden care products. garden shop discount store supermarket TOTAL Urban 11 20 15 46 Suburban 27 20 12 59 Rural 12 26 24 62 Total 50 66 51 167 [a] Fill in the table with the row percentages of each location category. Garden shop discount store supermarket Urban Suburban Rural [b] Write the null and alternate hypotheses for a test of...
"Analysis via Pivot Tables" Please respond to the following: Describe a situation where pivot tables could...
"Analysis via Pivot Tables" Please respond to the following: Describe a situation where pivot tables could be used to aid a business decision. Specify the question/problem management needs to resolve and explain the manner in which the pivot table results will provide a solution. You may use one (1) of the homework exercises as a basis for your response, or a company with which you are familiar.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT