Created
July 17, 2024 15:18
-
-
Save lsem/d0ada5fdd3fa0d02a8b72585da89daad to your computer and use it in GitHub Desktop.
bubble_sort.cpp
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
#include <type_traits> | |
#include <cstdint> | |
using namespace std; | |
// nseq | |
template<int... Is> struct nseq{}; | |
// prepend | |
template<int X, typename Seq> struct prepend; | |
template<int X, int... Is> struct prepend<X, nseq<Is...>> { | |
using result = nseq<X, Is...>; | |
}; | |
// conditional_v | |
template<bool P, int T, int E> struct conditional_v { static const int value = T; }; | |
template<int T, int E> struct conditional_v<false, T, E> { static const int value = E; }; | |
// bubble_sort1 | |
template<typename Seq> struct bubble_sort1; | |
template<int F, int S, int... Is> struct bubble_sort1<nseq<F, S, Is...>> { | |
using result = typename prepend<conditional_v<(F<S), F, S>::value, | |
typename bubble_sort1<typename std::conditional<(F<S), nseq<S,Is...>, nseq<F, Is...>>::type >::result>::result; | |
}; | |
template<int Last> struct bubble_sort1<nseq<Last>> { | |
using result = nseq<Last>; | |
}; | |
// bubble_sort_impl | |
template<size_t N, typename Seq> struct bubble_sort_impl; | |
template<size_t N, int... Is> struct bubble_sort_impl<N, nseq<Is...>> { | |
using result = typename bubble_sort_impl<N-1, typename bubble_sort1<nseq<Is...>>::result>::result; | |
}; | |
template<int... Is> struct bubble_sort_impl<0, nseq<Is...>> { | |
using result = nseq<Is...>; | |
}; | |
// bubble_sort | |
template<typename Seq> struct bubble_sort; | |
template<int ...Is> struct bubble_sort<nseq<Is...>> { | |
using result = typename bubble_sort_impl<sizeof...(Is), nseq<Is...>>::result; | |
}; | |
// debug | |
template<class ...Anything> struct debug_print; | |
int main() { | |
debug_print<bubble_sort<nseq<9, 8, 2, 6, 5, 4, 1>>::result> demo1; | |
debug_print<bubble_sort<nseq<234, 43, 55, 63, 5, 6, 235, 547>>::result> demo2; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment