Last active
January 17, 2020 17:25
-
-
Save sneppy/b003696b349e9fd726f51110ef4d54bf to your computer and use it in GitHub Desktop.
A C++ quicksort implementation that requires only a forward iterator to work
This file contains 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
template<typename T> | |
struct RemoveReference | |
{ | |
using Type = T; | |
}; | |
template<typename T> struct RemoveReference<T&> { using Type = T; }; | |
template<typename T> | |
inline void swap(T & a, T & b) | |
{ | |
T t = a; a = b, b = t; | |
} | |
template<typename T> | |
constexpr inline T && forward(typename RemoveReference<T>::Type & t) | |
{ | |
return static_cast<T&&>(t); | |
} | |
template<typename T> | |
constexpr inline T && forward(typename RemoveReference<T>::Type && t) | |
{ | |
return static_cast<T&&>(t); | |
} | |
template<typename It, typename CompareT> | |
void quicksort(It begin, It end, CompareT && cmp/* = [](const auto & a, const auto & b) { return int(a > b) - int(a < b); }*/) // C++14 or newer | |
{ | |
It i = begin, j = begin, k = begin; | |
if (i == end || ++i == end) | |
return; | |
else if (++i == end) | |
{ | |
if (cmp(*begin, *(++j)) > 0) swap(*begin, *j); | |
return; | |
} | |
i = j = begin; | |
for (++i, ++j; i != end; ++i) | |
if (cmp(*i, *begin) < 0) swap(*i, *(k = j)), ++j; | |
swap(*begin, *k); | |
quicksort(begin, k, forward<CompareT>(cmp)); | |
quicksort(j, end, forward<CompareT>(cmp)); | |
} | |
#include <stdio.h> | |
#include <vector> | |
int main() | |
{ | |
int x[] = {1, 4, 3, 2, 7, 1, 8, 1, 5, 5}; | |
std::vector<int> y{9, 8, 9, 5, 5, 1, 7, 2, 3, 1}; | |
auto cmp = [](int a, int b) { return int(a > b) - int(a < b); }; | |
quicksort(x, x + 10, cmp); | |
quicksort(y.begin(), y.end(), cmp); | |
printf("x | y\n"); | |
for (int i = 0; i < 10; ++i) printf("%d | %d\n", x[i], y[i]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment