Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created November 11, 2015 21:55
Show Gist options
  • Save goldsborough/370c926d606160a6e8fc to your computer and use it in GitHub Desktop.
Save goldsborough/370c926d606160a6e8fc to your computer and use it in GitHub Desktop.
Unoptimized single-function versions of quicksort.
#ifndef QUICK_SORT_SINGLE_FUNCTION_HPP
#define QUICK_SORT_SINGLE_FUNCTION_HPP
#include <iterator>
#include <utility>
template<typename Iterator>
void quick_sort(Iterator begin, Iterator end)
{
if (begin == end || std::next(begin) == end) return;
auto i = std::next(begin);
for (auto j = std::prev(end); i != j; ++i)
{
while (i != j && *i < *begin) ++i;
while (i != j && *j > *begin) --j;
if (i == j) break;
std::swap(*i, *j);
}
if (*i > *begin) --i;
std::swap(*i, *begin);
quick_sort(begin, i);
quick_sort(++i, end);
}
#endif /* QUICK_SORT_SINGLE_FUNCTION_HPP */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment