-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortRadix.cc
More file actions
73 lines (61 loc) · 1.87 KB
/
SortRadix.cc
File metadata and controls
73 lines (61 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <concepts>
#include <format>
#include <iostream>
#include <random>
#include "vector.hh"
// least significant digit first radix sort
template <class T>
requires std::integral<T>
void LSD(ns::vector<T> &A) {
constexpr int BYTES_PER_ELEMENT = sizeof(T);
constexpr int BITS_PER_BYTE = 8;
constexpr int RADIX = 1 << BITS_PER_BYTE;
constexpr int MASK = RADIX - 1;
int n = A.size();
ns::vector<T> aux(n);
for (int d = 0; d < BYTES_PER_ELEMENT; d++) {
ns::vector<int> count(RADIX + 1, 0);
for (int i = 0; i < n; i++) {
int c = (A[i] >> BITS_PER_BYTE * d) & MASK;
count[c + 1]++;
}
for (int r = 0; r < RADIX; r++) count[r + 1] += count[r];
if constexpr (std::is_signed_v<T>) {
if (d == BYTES_PER_ELEMENT - 1) {
int shift1 = count[RADIX] - count[RADIX / 2];
int shift2 = count[RADIX / 2];
// shift right positive integer
for (int r = 0; r < RADIX / 2; r++) count[r] += shift1;
// shift left negative integer
for (int r = RADIX / 2; r < RADIX; r++) count[r] -= shift2;
}
}
for (int i = 0; i < n; i++) {
int c = (A[i] >> BITS_PER_BYTE * d) & MASK;
aux[count[c]++] = A[i];
}
std::swap(A, aux);
std::cout << '\n';
std::ranges::for_each(
A, [](auto x) { std::cout << std::format("{:+}\t", x); });
std::cout << '\n';
}
}
int main() {
std::mt19937 mt(std::random_device{}());
std::uniform_int_distribution<int> rand(0x80000000, 0x7fffffff);
ns::vector<int> A(8);
for (auto &e : A) {
e = rand(mt);
std::cout << e << '\t';
}
std::cout << '\n';
LSD(A);
std::cout << '\n';
std::ranges::for_each(A,
[](auto x) { std::cout << std::format("{:+}\t", x); });
std::cout << "\n\n";
std::cout << std::format("{}",
std::ranges::is_sorted(A) ? "Sorted" : "Unsorted");
std::cout << '\n';
}