diff --git a/sorting/quick_sort_iterative.cpp b/sorting/quick_sort_iterative.cpp new file mode 100644 index 00000000000..da506c9c024 --- /dev/null +++ b/sorting/quick_sort_iterative.cpp @@ -0,0 +1,132 @@ +/** + * @file + * @brief Quick Sort without recursion. This method uses the stack instead. + * Both recursive and iterative implementations have O(n log n) best case + * and O(n^2) worst case. + * @details + * https://stackoverflow.com/questions/12553238/quicksort-iterative-or-recursive + * https://en.wikipedia.org/wiki/Quicksort + * https://www.geeksforgeeks.org/iterative-quick-sort/ + * @author [Sebe324](https://github.com/sebe324) + */ + +#include /// for std::cout +#include /// for std::vector +#include /// for std::stack +#include /// for std::is_sorted +#include /// for assert + + +/** + * @namespace sorting + * @brief Sorting algorithms + */ +namespace sorting { +/** + * @brief The partition function sorts the array from + * start to end and uses the last element as the pivot. + * @param arr the array to be sorted + * @param start starting index + * @param end ending index + * @return int next index of the pivot + */ +int partition(std::vector &arr, int start, int end) +{ + int pivot = arr[end]; + int index = start - 1; + + for (int j = start; j < end; j++) { + if (arr[j] <= pivot) { + std::swap(arr[++index], arr[j]); + } + } + + std::swap(arr[index + 1], arr[end]); + return index + 1; +} + +/** + * @brief The main sorting function + * @details The iterative quick sort uses + * the stack instead of recursion for saving + * and restoring the environment between calls. + * It does not need the end and start params, because + * it is not recursive. + * @param arr array to be sorted + * @return void + */ +void iterativeQuickSort(std::vector &arr) +{ + std::stack stack; + int start = 0; + int end = arr.size()-1; + stack.push(start); + stack.push(end); + + while(!stack.empty()) + { + end = stack.top(); + stack.pop(); + start = stack.top(); + stack.pop(); + + int pivotIndex = partition(arr,start,end); + + if(pivotIndex -1 > start) + { + stack.push(start); + stack.push(pivotIndex-1); + } + + if(pivotIndex+1 case1={100,534,1000000,553,10,61,2000,238,2756,9,12,56,30}; + std::cout<<"TEST 1\n"; + std::cout<<"Before: \n"; + for(auto x : case1) std::cout< case2={-10,-2,-5,-2,-3746,-785,-123, -452, -32456}; + std::cout<<"TEST 2\n"; + std::cout<<"Before: \n"; + for(auto x : case2) std::cout<