#include "quicksort.hpp" #include "utils.hpp" #include #include #include #include namespace { template T quicksort_partition(T begin, T end, const std::function()), decltype(*std::declval()))> comparer) { std::cout << "part: " << *begin << std::endl; assert(begin != end); // using difftype = decltype(std::declval() - std::declval()); const T piv = std::next(end, -1); T swapIfLesser = begin; while (swapIfLesser != piv && comparer(*swapIfLesser, *piv)) { swapIfLesser = std::next(swapIfLesser); } swapIfLesser = std::next(swapIfLesser); T active = std::next(swapIfLesser); while (active != piv) { if (comparer(*active, *piv)) { std::iter_swap(swapIfLesser, active); swapIfLesser = std::next(swapIfLesser); } active = std::next(active); } const T pivFinal = std::next(swapIfLesser); std::iter_swap(pivFinal, piv); return pivFinal; } } template void quicksort(T begin, T end, std::function()), decltype(*std::declval()))> comparer) { if (begin != end) { auto pivot = quicksort_partition(begin, end, comparer); quicksort(begin, pivot); quicksort(std::next(pivot), end); } } template void quicksort(T begin, T end) { const auto comparer = [](decltype(*std::declval()) f, decltype(*std::declval()) s){ return f < s; }; quicksort(begin, end, comparer); } int main() { //last value is to find OOB std::vector vec{12345, 1,5,3,2,5,7,9,-3,12,0, 9999}; arrayprint(vec.begin()+1, vec.end()-1); std::cout << std::endl; quicksort(vec.begin()+1, vec.end()-1); arrayprint(vec.begin()+1, vec.end()-1); std::cout << std::endl; std::cout << std::endl; std::vector vec2; arrayprint(vec2.begin(), vec2.end()); std::cout << std::endl; quicksort(vec2.begin(), vec2.end()); arrayprint(vec2.begin(), vec2.end()); std::cout << std::endl; return 0; }