In: Computer Science
Write an implementation of quicksort where the pivot is selected randomly.
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++)
Hoare (C++):
|