Created
May 30, 2020 05:45
-
-
Save xeno14/a7e49c7bbaee174858d4e9ed9468dd5c to your computer and use it in GitHub Desktop.
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
template <class IntegralType> | |
inline size_t idx(IntegralType x, size_t p, size_t d) { | |
// e.g. p=1 d=2 | |
// 101101 -> 11 | |
return ((x >> (p * d))) & ((1 << d) - 1); | |
} | |
template <class BidirectionalIterator> | |
void radix_sort(BidirectionalIterator first, BidirectionalIterator last, | |
int d = 8, int w = 64) { | |
using ValueType = | |
typename std::iterator_traits<BidirectionalIterator>::value_type; | |
static_assert(std::is_integral<ValueType>::value); | |
std::vector<size_t> count(1 << d); | |
std::vector<ValueType> a(first, last); | |
std::vector<ValueType> tmp(a.size()); | |
for (size_t p = 0; p < w / d; p++) { | |
std::fill(count.begin(), count.end(), 0); | |
for (auto x : a) ++count[idx(x, p, d)]; | |
std::partial_sum(count.begin(), count.end(), count.begin()); | |
for (auto it = a.rbegin(); it != a.rend(); ++it) { | |
tmp[--count[idx(*it, p, d)]] = *it; | |
} | |
std::swap(a, tmp); | |
} | |
std::copy(a.begin(), a.end(), first); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment