This is a kind of follow up to my previous sort implementation question with specific questions to insertion sort, and Modern C++ idioms. Anybody seeing this post can see how I got to this modern equivalent of a typical C-style sort you can find everywhere on the web by visiting my prior sorting review.
I am writing, as review for an interview, Modern C++ compliant versions of sorting algorithms I previously have seen. This post is about insertion sort, and insertion sort only.
// Shift/bubble each element toward the front into a sorted sub-array
template<typename BdIterator, typename Comparator = std::less<typename std::iterator_traits<BdIterator>::value_type>>
void sort_insertion(BdIterator beg, BdIterator end, Comparator cmp = Comparator())
{
BdIterator front, cur, prev;
// Assume the first element is sorted.
for (front = beg + 1u; front != end; ++front)
{
cur = front;
prev = cur - 1u;
// Bubble the "next" element towards the front by swapping it with its
// "prev" neighbor until it is in its sorted position.
while (cur != beg && cmp(*cur, *prev))
std::iter_swap(cur--, prev--);
}
}
As before, I am looking for any performance optimizations I may have missed in the algorithm itself, as well as Modern C++ constructs I may not be abiding by for this example.
One specific question I have deals with the unsigned integer I am adding and subtracting from the iterators to move to the next and previous values in the container. Since there is no way to get the type of container for the provided iterators, I do not see a way to get the size_type of the assumed container to add and subtract the correct types rather than just unsigned/signed integers.
The fact that I am subtracting prevents me from declaring the minimal Iterator template type as forward iterators (We are moving the iterator backwards). Is there a better way around this or should I just stick to making the minimum BiDirectionalIterators?