Skip to content

Instantly share code, notes, and snippets.

@xeno14
Created May 30, 2020 05:45
Show Gist options
  • Save xeno14/a7e49c7bbaee174858d4e9ed9468dd5c to your computer and use it in GitHub Desktop.
Save xeno14/a7e49c7bbaee174858d4e9ed9468dd5c to your computer and use it in GitHub Desktop.
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