I just started learning C++, and I'm taking an algorithms course on MIT Open Course Ware to get a better understanding of basic CS and the best practices in C++. Any comments on the structure of the algorithm (optimizations, etc) or best practices in C++ would be greatly appreciated!
#include <iterator>
#include <random>
namespace sort
{
namespace detail
{
template <typename ForwardIter, typename Compare>
ForwardIter randomized_partition(ForwardIter start, ForwardIter end, Compare less_than)
{
static std::default_random_engine gen;
std::uniform_int_distribution<long> rand_index(0, std::distance(start, end) - 1);
ForwardIter pivot = start + rand_index(gen);
std::iter_swap(start, pivot);
pivot = start;
ForwardIter less_than_pivot = start, greater_than_pivot = start + 1;
while (greater_than_pivot != end)
{
if ( less_than(*greater_than_pivot, *pivot) ) {
++less_than_pivot;
std::iter_swap(less_than_pivot, greater_than_pivot);
}
++greater_than_pivot;
}
std::iter_swap(pivot, less_than_pivot);
pivot = less_than_pivot;
return pivot;
}
}
template <typename ForwardIter, typename Compare = std::less<typename std::iterator_traits<ForwardIter>::value_type>>
void randomized_quick_sort(ForwardIter start, ForwardIter end, Compare less_than = Compare())
{
if (std::distance(start, end) > 1)
{
ForwardIter pivot = sort::detail::randomized_partition(start, end, less_than);
randomized_quick_sort(start, pivot, less_than);
randomized_quick_sort(pivot + 1, end, less_than);
}
}
}
less_thansince people might want to sort by a different key. I thinkstd::sortusescompas its parameter name. \$\endgroup\$operator+, sostart + 1should be replaced withstd::next(start). The same goes forstart + rand_index(gen);. \$\endgroup\$static_assertto ensure the passed iterator's category inherited fromstd::forward_iterator_tag. Anything else that I could improve on? \$\endgroup\$