Skip to content

Instantly share code, notes, and snippets.

@lsem
Last active July 27, 2022 12:32
Show Gist options
  • Save lsem/8dd4fd98a98a78fb740b01bb1516db92 to your computer and use it in GitHub Desktop.
Save lsem/8dd4fd98a98a78fb740b01bb1516db92 to your computer and use it in GitHub Desktop.
bubble_sort.cpp
#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 display_type_t;
int main() {
display_type_t<bubble_sort<nseq<9, 8, 2, 6, 5, 4, 1>>::result> demo1;
display_type_t<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