Skip to content

Instantly share code, notes, and snippets.

@asandroq
Last active April 14, 2020 14:21
Show Gist options
  • Save asandroq/532d9457f6bca4a97d24e43e335879b9 to your computer and use it in GitHub Desktop.
Save asandroq/532d9457f6bca4a97d24e43e335879b9 to your computer and use it in GitHub Desktop.
quicksort with bidirectional iterators
// Iterators need only be bidirectional, no random access needed
template <typename Iterator> void quicksort(const Iterator begin, const Iterator end)
{
// empty sequence
if (begin == end) {
return;
}
auto right = end;
right--;
// sequence with single element
if (begin == right) {
return;
}
auto left = begin;
while (left != right) {
if (*left <= *begin) {
left++;
} else if (*right > *begin) {
right--;
} else {
iter_swap(left, right);
}
}
// put pivot in place
if (*left > *begin) {
left--;
}
iter_swap(begin, left);
// sort subvectors
quicksort(begin, left);
quicksort(right, end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment