Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created October 24, 2015 22:27
Show Gist options
  • Save goldsborough/c0eddbd61817d792b206 to your computer and use it in GitHub Desktop.
Save goldsborough/c0eddbd61817d792b206 to your computer and use it in GitHub Desktop.
Hopefully finally edge-case-secure partitioning algorithm.
template<typename Iterator>
Iterator partition(Iterator begin, Iterator end)
{
auto pivot = begin++;
if (pivot == end || begin == end) return pivot;
for (--end; begin != end; ++begin)
{
while (begin != end && *begin < *pivot) ++begin;
while (begin != end && *end > *pivot) --end;
if (begin == end) break;
std::swap(*begin, *end);
}
if (*begin > *pivot) --begin;
std::swap(*begin, *pivot);
return begin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment