The code is generic, trying to support both STL iterators and normal C pointer arithmetic.
#include <cstdio>
#include <vector>
template<typename I>
void quick_sort_step(const I left, const I right)
{
auto pivot = *(left + (right - left) / 2);
auto l = left;
auto r = right;
while (l <= r) {
while (*l < pivot)
++l;
while (*r > pivot)
--r;
if (l <= r)
std::swap(*l++, *r--);
}
if (left < r)
quick_sort_step(left, r);
if (l < right)
quick_sort_step(l, right);
}
template<typename I>
void quick_sort(const I begin, const I end)
{
if (end - begin > 1)
quick_sort_step(begin, std::prev(end));
}
int main()
{
typedef std::vector<int> list;
list l { 5, 0, 2, 4, 1, 3, 9, 8, 7, 6 };
quick_sort(l.begin(), l.end());
for (auto i : l) {
printf("%i ", i);
}
return 0;
}
::sort()
before it is used. Use forward declaration or movequick_sort()
. \$\endgroup\$l
andr
in yoursort
function? If they are pointers, the operation<=
may not be valid. Usually, pointers need to be converted to an integral type before comparison. There is no check thatright
is greater thanleft
. Are these pointers also? \$\endgroup\$