#ifndef SORT_H
#define SORT_H
#include <iostream>
#include <ctime>
namespace jdw {
template <typename Iterator, typename Comp>
Iterator partition(Iterator first, Iterator last, Comp comp)
{
if (first >= last) {
return last;
}
srand(time(0));
int random = rand() % (last - first);
std::swap(*first, *(first + random));
auto pivot = *first;
auto left = first;
auto right = last - 1;
while (left < right) {
while (left < right && (comp(pivot, *right) || !comp(*right, pivot))) --right;
while (left < right && (comp(*left, pivot) || !comp(pivot, *left))) ++left;
std::swap(*left, *right);
}
std::swap(*left, *first);
return left;
}
template <typename Iterator, typename Comp>
void quickSort_aux(Iterator first, Iterator last, Comp comp)
{
auto iter = partition(first, last, comp);
if (iter == last) return ;
quickSort_aux(first, iter, comp);
quickSort_aux(iter + 1, last, comp);
}
template <typename Iterator, typename Comp = std::less<typename Iterator::value_type>>
void sort(Iterator first, Iterator last, Comp comp = std::less<typename Iterator::value_type>())
{
quickSort_aux(first, last, comp);
}
template<typename Container>
void print(const Container& container) {
for (auto& e : container) {
std::cout << e << " ";
}
std::cout << std::endl;
}
}
#endif
#include "sort.h"
#include <vector>
template <typename T>
void test_jdw_quicksort(std::vector<T>& nums) {
jdw::sort(nums.begin(), nums.end());
jdw::print(nums);
jdw::sort(nums.begin(), nums.end(), std::greater<T>());
jdw::print(nums);
}
int main() {
std::vector<int> nums1{5,9,-85,6,20,0,-6,33,44,23,99};
test_jdw_quicksort(nums1);
std::vector<int> nums2(20, 0);
test_jdw_quicksort(nums2);
std::vector<char> chars{'3', 'a', 'A', 'S', 'D', '0', '+', '*', '&'};
test_jdw_quicksort(chars);
std::vector<double> ds{1.2, -2.3, 4.5, 4.77, 5123, 3.1321, -22222, 31.323, 11.0};
test_jdw_quicksort(ds);
}