25
loading...
This website collects cookies to deliver better user experience
std::sort
) and radix sort, based on the common bucketing approach.Here are my implementations of bucket-based and count-based radix sort, in C++:
#include <vector>
typedef std::vector<uint64_t> TestCase;
typedef std::vector<uint64_t> Bucket;
template<size_t K = 8> void radix_bucket_sort(TestCase& input)
{
constexpr size_t slots = 1 << K;
constexpr TestCase::value_type mask = slots - 1;
constexpr size_t bits = sizeof(TestCase::value_type) * 8;
for (int r = 0; r < bits; r += K) {
Bucket radixes[slots];
for (auto n : input) {
radixes[(n >> r) & mask].push_back(n);
}
input.clear();
for (auto& bucket : radixes) {
input.insert(input.end(), bucket.begin(), bucket.end());
}
}
}
template<size_t K = 8> void radix_count_sort(TestCase& input)
{
constexpr size_t slots = 1 << K;
constexpr TestCase::value_type mask = slots - 1;
constexpr size_t bits = sizeof(TestCase::value_type) * 8;
TestCase output(input.size());
for (int r = 0; r < bits; r += K) {
size_t counts[slots] = {0};
for (auto n : input) {
++counts[(n >> r) & mask];
}
size_t accum = 0;
for (auto& n : counts) {
n += accum;
accum = n;
}
for (auto iter = input.rbegin(); iter != input.rend(); ++iter) {
output[--counts[(*iter >> r) & mask]] = *iter;
}
std::swap(input, output);
}
}
big-o-2.cpp
std::sort
, and both bucket and counting radix sort using a 4- and 8-bit radix: (raw data)std::sort
at around N=13000std::sort
until fairly large input sizes, even with all of the overall performance improvements which have happened (after all, std::sort
has gotten faster too).std::sort
still wins for input sizes of a few hundred values, and of course the maintenance overhead of using std::sort
is way lower.25