Last active
April 14, 2020 14:21
-
-
Save asandroq/532d9457f6bca4a97d24e43e335879b9 to your computer and use it in GitHub Desktop.
quicksort with bidirectional iterators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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