This is a follow-up to
Like the previous code, this does not optimize for containers with large numbers of duplicate elements. How can I improve this code, particularly with iterators?
template<typename C>
void insertion_sort(C low, C high) {
for (auto i = low; i < high; ++i) {
for (auto j = i; j != low && *j < *(j-1); --j) {
std::swap(*j, *(j-1));
}
}
}
template<typename C, typename I>
I partition(C& c, I low, I high) {
auto p = *low;
I i = low;
I j = high;
while (true) {
while (i+1 != std::end(c) && *(++i) < p) {
if (i == high) {
break;
}
}
while (p < *(--j)) { }
if (i >= j) {
break;
}
std::swap(*i, *j);
}
std::swap(*low, *j);
return j;
}
template<typename C, typename I>
void sort(C& c, I low, I high) {
if (high <= low+15) {
insertion_sort(low, high);
return;
}
I p = partition(c, low,high);
sort(c, low, p);
sort(c, p+1,high);
}
template<typename C>
void sort(C& c) {
if (std::begin(c) == std::end(c)) {
throw std::out_of_range("no size");
}
if (c.size() == 1) {
return;
}
std::random_shuffle(std::begin(c), std::end(c));
sort(c, std::begin(c), std::end(c));
}