# Algorithms_in_C++: sorting/random_pivot_quick_sort.cpp File Reference

Loading...
Searching...
No Matches
random_pivot_quick_sort.cpp File Reference

Implementation of the Random Pivot Quick Sort algorithm. More...

`#include <algorithm>`
`#include <array>`
`#include <cassert>`
`#include <ctime>`
`#include <iostream>`
`#include <tuple>`
Include dependency graph for random_pivot_quick_sort.cpp:

## Classes

class | TestCases
| class encapsulating the necessary test cases More...

## Namespaces

namespace | sorting
| for working with vectors
namespace | random_pivot_quick_sort
| Functions for the Random Pivot Quick Sort implementation.

## Functions

template<size_t T>
void | sorting::random_pivot_quick_sort::showArray (std::array< int64_t, T > arr)
| Utility function to print the array. More...
int64_t | sorting::random_pivot_quick_sort::getRandomIndex (int64_t start, int64_t end)
| Takes the start and end indices of an array and returns a random int64_teger between the range of those two for selecting pivot element. More...
template<size_t size>
std::tuple< int64_t, std::array< int64_t, size > > | sorting::random_pivot_quick_sort::partition (std::array< int64_t, size > arr, int64_t start, int64_t end)
| A partition function which handles the partition logic of quick sort. More...
template<size_t size>
std::array< int64_t, size > | sorting::random_pivot_quick_sort::quickSortRP (std::array< int64_t, size > arr, int64_t start, int64_t end)
| Random pivot quick sort function. This function is the starting point of the algorithm. More...
template<size_t size>
std::array< int64_t, size > | sorting::random_pivot_quick_sort::generateUnsortedArray (int64_t from, int64_t to)
| A function utility to generate unsorted array of given size and range. More...
static void | test ()
| Self-test implementations. More...
int | main (int argc, char *argv[])
| Main function. More...

## Detailed Description

Implementation of the Random Pivot Quick Sort algorithm.

- A random pivot quick sort algorithm is pretty much same as quick sort with a difference of having a logic of selecting next pivot element from the input array.
- Where in quick sort is fast, but still can give you the time complexity of O(n^2) in worst case.
- To avoid hitting the time complexity of O(n^2), we use the logic of randomize the selection process of pivot element.

           ### Logic
               * The logic is pretty simple, the only change is in the

  partitioning algorithm, which is selecting the pivot element.
  - Instead of selecting the last or the first element from array for pivot we use a random index to select pivot element.
  - This avoids hitting the O(n^2) time complexity in practical use cases.

          ### Partition Logic
              * Partitions are done such as numbers lower than the "pivot"

    element is arranged on the left side of the "pivot", and number larger than the "pivot" element are arranged on the right part of the array.

          ### Algorithm
              * Select the pivot element randomly using getRandomIndex() function

    from this namespace.

Initialize the pInd (partition index) from the start of the array.

- Loop through the array from start to less than end. (from start to < end). (Inside the loop) :-
  - Check if the current element (arr[i]) is less than the pivot element in each iteration.
  - If current element in the iteration is less than the pivot element, then swap the elements at current index (i) and partition index (pInd) and increment the partition index by one.
- At the end of the loop, swap the pivot element with partition index element.
- Return the partition index from the function.

Author
  Nitin Sharma

## Function Documentation

## generateUnsortedArray()

template<size_t size>

std::array< int64_t, size > sorting::random_pivot_quick_sort::generateUnsortedArray | ( | int64_t | from,
|  | int64_t | to
| ) |  |

A function utility to generate unsorted array of given size and range.

Template Parameters

  size | Size of the output array.

Parameters

  from | Stating of the range.
  to | Ending of the range.

Returns
  std::array<int64_t , size> Unsorted array of specified size.

{
srand(time(nullptr));
std::array<int64_t, size> unsortedArray{};
assert(from < to);
int64_t i = 0;
while (i < size) {
int64_t randomNum = from + rand() % (to - from + 1);
if (randomNum) {
unsortedArray[i] = randomNum;
i++;
}
}
return unsortedArray;
}
std::array
std::rand
T rand(T... args)
std::srand
T srand(T... args)
std::time
T time(T... args)
Here is the call graph for this function:

## getRandomIndex()

int64_t sorting::random_pivot_quick_sort::getRandomIndex | ( | int64_t | start,
|  | int64_t | end
| ) |  |

Takes the start and end indices of an array and returns a random int64_teger between the range of those two for selecting pivot element.

Parameters

  start | The starting index.
  end | The ending index.

Returns
  int64_t A random number between start and end index.

{
srand(time(nullptr)); // Initialize random number generator.
int64_t randomPivotIndex = start + rand() % (end - start + 1);
return randomPivotIndex;
}
std::end
T end(T... args)
Here is the call graph for this function:

## main()

int main | ( | int | argc,
|  | char * | argv[]
| ) |  |

Main function.

Parameters

  argc | commandline argument count (ignored)
  argv | commandline array of arguments (ignored)

Returns
  0 on exit

{
test(); // Executes various test cases.
const int64_t inputSize = 10;
std::array<int64_t, inputSize> unsorted_array =
sorting::random_pivot_quick_sort::generateUnsortedArray<inputSize>(
50, 1000);
std::cout << "Unsorted array is : " << std::endl;
sorting::random_pivot_quick_sort::showArray(unsorted_array);
std::array<int64_t, inputSize> sorted_array =
sorting::random_pivot_quick_sort::quickSortRP(
unsorted_array, 0, unsorted_array.size() - 1);
std::cout << "Sorted array is : " << std::endl;
sorting::random_pivot_quick_sort::showArray(sorted_array);
return 0;
}
std::cout
std::endl
T endl(T... args)
sorting::random_pivot_quick_sort::quickSortRP
std::array< int64_t, size > quickSortRP(std::array< int64_t, size > arr, int64_t start, int64_t end)
Random pivot quick sort function. This function is the starting point of the algorithm.
Definition: random_pivot_quick_sort.cpp:130
test
static void test()
Self-test implementations.
Definition: random_pivot_quick_sort.cpp:312
sorting::random_pivot_quick_sort::showArray
void showArray(std::array< int64_t, T > arr)
Utility function to print the array.
Definition: random_pivot_quick_sort.cpp:73
std::array::size
T size(T... args)
Here is the call graph for this function:

## partition()

template<size_t size>

std::tuple< int64_t, std::array< int64_t, size > > sorting::random_pivot_quick_sort::partition | ( | std::array< int64_t, size > | arr,
|  | int64_t | start,
|  | int64_t | end
| ) |  |

A partition function which handles the partition logic of quick sort.

Template Parameters

  size | size of the array to be passed as argument.

Parameters

  start | The start index of the passed array
  end | The ending index of the passed array

Returns
  std::tuple<int64_t , std::array<int64_t , size>> A tuple of pivot index and pivot sorted array.

{
int64_t pivot = arr[end]; // Randomly selected element will be here from
// caller function (quickSortRP()).
int64_t pInd = start;
for (int64_t i = start; i < end; i++) {
if (arr[i] <= pivot) {
std::swap(arr[i], arr[pInd]); // swapping the elements from current
// index to pInd.
pInd++;
}
}
std::swap(arr[pInd],
arr[end]); // swapping the pivot element to its sorted position
return std::make_tuple(pInd, arr);
}
std::make_tuple
T make_tuple(T... args)
std::swap
T swap(T... args)
Here is the call graph for this function:

## quickSortRP()

template<size_t size>

std::array< int64_t, size > sorting::random_pivot_quick_sort::quickSortRP | ( | std::array< int64_t, size > | arr,
|  | int64_t | start,
|  | int64_t | end
| ) |  |

Random pivot quick sort function. This function is the starting point of the algorithm.

Template Parameters

  size | size of the array to be passed as argument.

Parameters

  start | The start index of the passed array
  end | The ending index of the passed array

Returns
  std::array<int64_t , size> A fully sorted array in ascending order.

{
if (start < end) {
int64_t randomIndex = getRandomIndex(start, end);
// switching the pivot with right most bound.
std::swap(arr[end], arr[randomIndex]);
int64_t pivotIndex = 0;
// getting pivot index and pivot sorted array.
std::tie(pivotIndex, arr) = partition(arr, start, end);
// Recursively calling
std::array<int64_t, arr.size()> rightSortingLeft =
quickSortRP(arr, start, pivotIndex - 1);
std::array<int64_t, arr.size()> full_sorted =
quickSortRP(rightSortingLeft, pivotIndex + 1, end);
arr = full_sorted;
}
return arr;
}
std::partition
T partition(T... args)
sorting::random_pivot_quick_sort::getRandomIndex
int64_t getRandomIndex(int64_t start, int64_t end)
Takes the start and end indices of an array and returns a random int64_teger between the range of tho...
Definition: random_pivot_quick_sort.cpp:88
std::tie
T tie(T... args)
Here is the call graph for this function:

## showArray()

template<size_t T>

void sorting::random_pivot_quick_sort::showArray | ( | std::array< int64_t, T > | arr | ) |

Utility function to print the array.

Template Parameters

  T | size of the array

Parameters

  arr | array used to print its content

Returns
  void

{
for (int64_t i = 0; i < arr.size(); i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
Here is the call graph for this function:

## test()

static void test | ( |  | ) |

static

Self-test implementations.

Returns
  void

{
TestCases tc = TestCases();
tc.runTests();
}
TestCases
class encapsulating the necessary test cases
Definition: inorder_successor_of_bst.cpp:225
TestCases::runTests
void runTests()
Executes test cases.
Definition: inorder_successor_of_bst.cpp:243
Here is the call graph for this function: