Most quicksort examples online use C-style arrays and indexes. I have written below quicksort implementation with STL style iterators. It looks fine to me, but I feel like I may be making more than necessary copies of iterators. I am open for any suggestions/improvements:
#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
#include <iterator>
template <typename Iter>
inline Iter partition(const Iter& beg, const Iter& end) {
using std::swap;
assert(beg != end);
auto piv = end;
--piv; // Pivot is the last element
auto index_small = beg;
for (auto index_large = beg; index_large != piv; ++index_large) {
if (*index_large <= *piv) {
swap(*index_large, *index_small);
++index_small;
}
}
swap(*index_small, *piv);
return index_small;
}
template <typename Iter>
void quick_sort(const Iter& beg, const Iter& end) {
if (end - beg > 1) {
const auto& piv = partition(beg, end);
quick_sort(beg, piv);
quick_sort(piv, end);
}
}
// Test
int main() {
std::vector<int> vec{ 19, 54, 53, 9, 3, 96, 40, 36, 96, 43, 45,
78, 57, 6, 12, 100, 36, 15, 27, 45, 80, 39,
10, 71, 100, 15, 41, 43, 20, 32, 61, 2, 55,
33, 85, 32, 11, 50, 25, 17, 75, 74, 39, 49,
50, 17, 18, 55, 63, 81, };
quick_sort(vec.begin(), vec.end());
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
}