|
| 1 | +/** |
| 2 | + * @file |
| 3 | + * @brief Implementation of the [Random Pivot Quick Sort](https://www.sanfoundry.com/cpp-program-implement-quick-sort-using-randomisation) algorithm. |
| 4 | + * @details |
| 5 | + * * A random pivot quick sort algorithm is pretty much same as quick sort with a difference of having a logic of |
| 6 | + * selecting next pivot element from the input array. |
| 7 | + * * Where in quick sort is fast, but still can give you the time complexity of O(n^2) in worst case. |
| 8 | + * * To avoid hitting the time complexity of O(n^2), we use the logic of randomize the selection process of pivot |
| 9 | + * element. |
| 10 | + * |
| 11 | + * ### Logic |
| 12 | + * * The logic is pretty simple, the only change is in the partitioning algorithm, which is selecting the |
| 13 | + * pivot element. |
| 14 | + * * Instead of selecting the last or the first element from array for pivot we use a random index to select |
| 15 | + * pivot element. |
| 16 | + * * This avoids hitting the O(n^2) time complexity in practical use cases. |
| 17 | + * |
| 18 | + * ### Partition Logic |
| 19 | + * * Partitions are done such as numbers lower than the "pivot" element is arranged on the left side of the "pivot", |
| 20 | + * and number larger than the "pivot" element are arranged on the right part of the array. |
| 21 | + * |
| 22 | + * ### Algorithm |
| 23 | + * * Select the pivot element randomly using getRandomIndex() function from this namespace. |
| 24 | + * * Initialize the pInd (partition index) from the start of the array. |
| 25 | + * * Loop through the array from start to less than end. (from start to < end). |
| 26 | + * (Inside the loop) :- |
| 27 | + * * Check if the current element (arr[i]) is less than the pivot element in each iteration. |
| 28 | + * * If current element in the iteration is less than the pivot element, |
| 29 | + * then swap the elements at current index (i) and partition index (pInd) and increment the partition index by one. |
| 30 | + * * At the end of the loop, swap the pivot element with partition index element. |
| 31 | + * * Return the partition index from the function. |
| 32 | + * |
| 33 | + * @author [Nitin Sharma](https://github.com/foo290) |
| 34 | + */ |
| 35 | + |
| 36 | +#include <iostream> /// for IO operations |
| 37 | +#include <ctime> /// for initializing random number generator |
| 38 | +#include <cassert> /// for assert |
| 39 | +#include <algorithm> /// for std::is_sorted(), std::swap() |
| 40 | +#include <array> /// for std::array |
| 41 | +#include <tuple> /// for returning multiple values form a function at once |
| 42 | + |
| 43 | +/** |
| 44 | + * @namespace sorting |
| 45 | + * @brief Sorting algorithms |
| 46 | + */ |
| 47 | +namespace sorting { |
| 48 | +/** |
| 49 | + * @brief Functions for the [Random Pivot Quick Sort](https://www.sanfoundry.com/cpp-program-implement-quick-sort-using-randomisation) implementation |
| 50 | + * @namespace random_pivot_quick_sort |
| 51 | + */ |
| 52 | + namespace random_pivot_quick_sort { |
| 53 | + /** |
| 54 | + * @brief Utility function to print the array |
| 55 | + * @tparam T size of the array |
| 56 | + * @param arr array used to print its content |
| 57 | + * @returns void |
| 58 | + * */ |
| 59 | + template<size_t T> |
| 60 | + void showArray(std::array<int64_t , T> arr) { |
| 61 | + for (int64_t i = 0; i < arr.size(); i++) { |
| 62 | + std::cout << arr[i] << " "; |
| 63 | + } |
| 64 | + std::cout << std::endl; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * @brief Takes the start and end indices of an array and returns a random int64_teger between the range of those two |
| 69 | + * for selecting pivot element. |
| 70 | + * |
| 71 | + * @param start The starting index. |
| 72 | + * @param end The ending index. |
| 73 | + * @returns int64_t A random number between start and end index. |
| 74 | + * */ |
| 75 | + int64_t getRandomIndex(int64_t start, int64_t end) { |
| 76 | + srand(time(nullptr)); // Initialize random number generator. |
| 77 | + int64_t randomPivotIndex = start + rand() % (end - start + 1); |
| 78 | + return randomPivotIndex; |
| 79 | + } |
| 80 | + |
| 81 | + /** |
| 82 | + * @brief A partition function which handles the partition logic of quick sort. |
| 83 | + * @tparam size size of the array to be passed as argument. |
| 84 | + * @param start The start index of the passed array |
| 85 | + * @param end The ending index of the passed array |
| 86 | + * @returns std::tuple<int64_t , std::array<int64_t , size>> A tuple of pivot index and pivot sorted array. |
| 87 | + */ |
| 88 | + template<size_t size> |
| 89 | + std::tuple<int64_t , std::array<int64_t , size>> partition(std::array<int64_t , size> arr, int64_t start, int64_t end) { |
| 90 | + |
| 91 | + int64_t pivot = arr[end]; // Randomly selected element will be here from caller function (quickSortRP()). |
| 92 | + int64_t pInd = start; |
| 93 | + |
| 94 | + for (int64_t i = start; i < end; i++) { |
| 95 | + if (arr[i] <= pivot) { |
| 96 | + std::swap(arr[i], arr[pInd]); // swapping the elements from current index to pInd. |
| 97 | + pInd++; |
| 98 | + } |
| 99 | + } |
| 100 | + std::swap(arr[pInd], arr[end]); // swapping the pivot element to its sorted position |
| 101 | + return std::make_tuple(pInd, arr); |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * @brief Random pivot quick sort function. This function is the starting point of the algorithm. |
| 106 | + * @tparam size size of the array to be passed as argument. |
| 107 | + * @param start The start index of the passed array |
| 108 | + * @param end The ending index of the passed array |
| 109 | + * @returns std::array<int64_t , size> A fully sorted array in ascending order. |
| 110 | + */ |
| 111 | + template<size_t size> |
| 112 | + std::array<int64_t , size> quickSortRP(std::array<int64_t , size> arr, int64_t start, int64_t end) { |
| 113 | + if (start < end) { |
| 114 | + |
| 115 | + int64_t randomIndex = getRandomIndex(start, end); |
| 116 | + |
| 117 | + // switching the pivot with right most bound. |
| 118 | + std::swap(arr[end], arr[randomIndex]); |
| 119 | + |
| 120 | + int64_t pivotIndex = 0; |
| 121 | + // getting pivot index and pivot sorted array. |
| 122 | + std::tie(pivotIndex, arr) = partition(arr, start, end); |
| 123 | + |
| 124 | + // Recursively calling |
| 125 | + std::array<int64_t , arr.size()> rightSortingLeft = quickSortRP(arr, start, pivotIndex - 1); |
| 126 | + std::array<int64_t , arr.size()> full_sorted = quickSortRP(rightSortingLeft, pivotIndex + 1, end); |
| 127 | + arr = full_sorted; |
| 128 | + } |
| 129 | + return arr; |
| 130 | + } |
| 131 | + |
| 132 | + /** |
| 133 | + * @brief A function utility to generate unsorted array of given size and range. |
| 134 | + * @tparam size Size of the output array. |
| 135 | + * @param from Stating of the range. |
| 136 | + * @param to Ending of the range. |
| 137 | + * @returns std::array<int64_t , size> Unsorted array of specified size. |
| 138 | + * */ |
| 139 | + template<size_t size> |
| 140 | + std::array<int64_t , size> generateUnsortedArray(int64_t from, int64_t to) { |
| 141 | + srand(time(nullptr)); |
| 142 | + std::array<int64_t , size> unsortedArray{}; |
| 143 | + assert(from < to); |
| 144 | + int64_t i = 0; |
| 145 | + while (i < size) { |
| 146 | + int64_t randomNum = from + rand() % (to - from + 1); |
| 147 | + if (randomNum) { |
| 148 | + unsortedArray[i] = randomNum; |
| 149 | + i++; |
| 150 | + } |
| 151 | + } |
| 152 | + return unsortedArray; |
| 153 | + } |
| 154 | + |
| 155 | +} // namespace random_pivot_quick_sort |
| 156 | +} // namespace sorting |
| 157 | + |
| 158 | +/** |
| 159 | + * @brief a class containing the necessary test cases |
| 160 | + */ |
| 161 | +class TestCases { |
| 162 | +private: |
| 163 | + /** |
| 164 | + * @brief A function to print64_t given message on console. |
| 165 | + * @tparam T Type of the given message. |
| 166 | + * @returns void |
| 167 | + * */ |
| 168 | + template<typename T> |
| 169 | + void log(T msg) { |
| 170 | + // It's just to avoid writing cout and endl |
| 171 | + std::cout << "[TESTS] : ---> " << msg << std::endl; |
| 172 | + } |
| 173 | + |
| 174 | +public: |
| 175 | + /** |
| 176 | + * @brief Executes test cases |
| 177 | + * @returns void |
| 178 | + * */ |
| 179 | + void runTests() { |
| 180 | + log("Running Tests..."); |
| 181 | + |
| 182 | + testCase_1(); |
| 183 | + testCase_2(); |
| 184 | + testCase_3(); |
| 185 | + |
| 186 | + log("Test Cases over!"); |
| 187 | + std::cout << std::endl; |
| 188 | + } |
| 189 | + |
| 190 | + /** |
| 191 | + * @brief A test case with single input |
| 192 | + * @returns void |
| 193 | + * */ |
| 194 | + void testCase_1() { |
| 195 | + const int64_t inputSize = 1; |
| 196 | + log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); |
| 197 | + log("This is test case 1 for Random Pivot Quick Sort Algorithm : "); |
| 198 | + log("Description:"); |
| 199 | + log(" EDGE CASE : Only contains one element"); |
| 200 | + std::array<int64_t , inputSize> unsorted_arr{2}; |
| 201 | + |
| 202 | + int64_t start = 0; |
| 203 | + int64_t end = unsorted_arr.size() - 1; // length - 1 |
| 204 | + |
| 205 | + log("Running algorithm of data of length 50 ..."); |
| 206 | + std::array<int64_t , unsorted_arr.size()> sorted_arr = sorting::random_pivot_quick_sort::quickSortRP( |
| 207 | + unsorted_arr, start, end |
| 208 | + ); |
| 209 | + log("Algorithm finished!"); |
| 210 | + |
| 211 | + log("Checking assert expression..."); |
| 212 | + assert(std::is_sorted(sorted_arr.begin(), sorted_arr.end())); |
| 213 | + log("Assertion check passed!"); |
| 214 | + |
| 215 | + log("[PASS] : TEST CASE 1 PASS!"); |
| 216 | + log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); |
| 217 | + } |
| 218 | + |
| 219 | + /** |
| 220 | + * @brief A test case with input array of length 500 |
| 221 | + * @returns void |
| 222 | + * */ |
| 223 | + void testCase_2() { |
| 224 | + const int64_t inputSize = 500; |
| 225 | + log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); |
| 226 | + log("Description:"); |
| 227 | + log(" BIG INPUT : Contains 500 elements and repeated elements"); |
| 228 | + log("This is test case 2 for Random Pivot Quick Sort Algorithm : "); |
| 229 | + std::array<int64_t , inputSize> unsorted_arr = sorting::random_pivot_quick_sort::generateUnsortedArray<inputSize>(1, 10000); |
| 230 | + |
| 231 | + int64_t start = 0; |
| 232 | + int64_t end = unsorted_arr.size() - 1; // length - 1 |
| 233 | + |
| 234 | + log("Running algorithm of data of length 500 ..."); |
| 235 | + std::array<int64_t , unsorted_arr.size()> sorted_arr = sorting::random_pivot_quick_sort::quickSortRP( |
| 236 | + unsorted_arr, start, end |
| 237 | + ); |
| 238 | + log("Algorithm finished!"); |
| 239 | + |
| 240 | + log("Checking assert expression..."); |
| 241 | + assert(std::is_sorted(sorted_arr.begin(), sorted_arr.end())); |
| 242 | + log("Assertion check passed!"); |
| 243 | + |
| 244 | + log("[PASS] : TEST CASE 2 PASS!"); |
| 245 | + log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); |
| 246 | + } |
| 247 | + |
| 248 | + /** |
| 249 | + * @brief A test case with array of length 1000. |
| 250 | + * @returns void |
| 251 | + * */ |
| 252 | + void testCase_3() { |
| 253 | + const int64_t inputSize = 1000; |
| 254 | + log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); |
| 255 | + log("This is test case 3 for Random Pivot Quick Sort Algorithm : "); |
| 256 | + log("Description:"); |
| 257 | + log(" LARGE INPUT : Contains 1000 elements and repeated elements"); |
| 258 | + std::array<int64_t , inputSize> unsorted_arr = sorting::random_pivot_quick_sort::generateUnsortedArray<inputSize>(1, 10000); |
| 259 | + |
| 260 | + int64_t start = 0; |
| 261 | + int64_t end = unsorted_arr.size() - 1; // length - 1 |
| 262 | + |
| 263 | + log("Running algorithm..."); |
| 264 | + std::array<int64_t , unsorted_arr.size()> sorted_arr = sorting::random_pivot_quick_sort::quickSortRP( |
| 265 | + unsorted_arr, start, end |
| 266 | + ); |
| 267 | + log("Algorithm finished!"); |
| 268 | + |
| 269 | + log("Checking assert expression..."); |
| 270 | + assert(std::is_sorted(sorted_arr.begin(), sorted_arr.end())); |
| 271 | + log("Assertion check passed!"); |
| 272 | + |
| 273 | + log("[PASS] : TEST CASE 3 PASS!"); |
| 274 | + log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); |
| 275 | + } |
| 276 | +}; |
| 277 | + |
| 278 | + |
| 279 | +/** |
| 280 | + * @brief Self-test implementations |
| 281 | + * @returns void |
| 282 | + */ |
| 283 | +static void test() { |
| 284 | + TestCases tc = TestCases(); |
| 285 | + tc.runTests(); |
| 286 | +} |
| 287 | + |
| 288 | +/** |
| 289 | + * @brief Main function |
| 290 | + * @param argc commandline argument count (ignored) |
| 291 | + * @param argv commandline array of arguments (ignored) |
| 292 | + * @returns 0 on exit |
| 293 | + */ |
| 294 | +int main(int argc, char *argv[]) { |
| 295 | + test(); // Executes various test cases. |
| 296 | + |
| 297 | + const int64_t inputSize = 10; |
| 298 | + std::array<int64_t , inputSize> unsorted_array = sorting::random_pivot_quick_sort::generateUnsortedArray<inputSize>(50, 1000); |
| 299 | + std::cout << "Unsorted array is : " << std::endl; |
| 300 | + sorting::random_pivot_quick_sort::showArray(unsorted_array); |
| 301 | + |
| 302 | + std::array<int64_t , inputSize> sorted_array = sorting::random_pivot_quick_sort::quickSortRP( |
| 303 | + unsorted_array, 0, |
| 304 | + unsorted_array.size() - 1 |
| 305 | + ); |
| 306 | + std::cout << "Sorted array is : " << std::endl; |
| 307 | + sorting::random_pivot_quick_sort::showArray(sorted_array); |
| 308 | + return 0; |
| 309 | +} |
0 commit comments