1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
# include <algorithm>
# include <iterator>
namespace {
template <typename Iterator, typename Comp> void
quicksort(Iterator const begin, Iterator const end, Comp const comp) {
if (begin != end) {
auto const middle = std::distance(begin,end) / 2;
auto const pivot = std::next(begin, middle);
Iterator middle1 = std::partition(begin, end,
[=] (auto const& element) {
return comp(element, *pivot);
});
Iterator middle2 = std::partition(middle1, end,
[=] (auto const & element) {
return ! comp(*pivot, element);
});
quicksort(begin, middle1, comp);
quicksort(middle2, end, comp);
}
}
}
# include <random>
# include <iostream>
# include <vector>
int main (int, char **) {
std::vector <int> foo { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(foo.begin(), foo.end(), g);
std::cout << "shuffled array" << "\n";
for (auto e: foo) { std::cout << e << " "; }
std::cout << "\n\n";
std::cout << "sorted array" << "\n";
quicksort(foo.begin(), foo.end(), std::less<int>{});
for (auto e: foo) { std::cout << e << " "; }
std::cout << "\n";
std::cout << "Is sorted? " << std::boolalpha
<< std::is_sorted(foo.begin(), foo.end(), std::less<int>{}) << "\n";
}
|