-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLSD.h
116 lines (95 loc) · 3.14 KB
/
LSD.h
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#ifndef CH5_LSD_H
#define CH5_LSD_H
#include <string>
#include <vector>
using std::string;
using std::vector;
/**
* The {@code LSD} class provides static methods for sorting an
* array of <em>w</em>-character strings or 32-bit integers using LSD radix sort.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/51radix">Section 5.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
class LSD {
public:
// do not instantiate
LSD() = delete;
/**
* Rearranges the array of W-character strings in ascending order.
*
* @param a the array to be sorted
* @param w the number of characters per string
*/
static void sort(vector<string> &a, int w) {
int n = a.size();
int R = 256; // extend ASCII alphabet size
vector<string> aux(n);
for (int d = w - 1; d >= 0; d--) {
// sort by key-indexed counting on dth character
// compute frequency counts
vector<int> count(R + 1);
for (int i = 0; i < n; i++)
count[a[i][d] + 1]++;
// compute cumulates
for (int r = 0; r < R; r++)
count[r + 1] += count[r];
// move data
for (int i = 0; i < n; i++)
aux[count[a[i][d]]++] = a[i];
// copy back
for (int i = 0; i < n; i++)
a[i] = aux[i];
}
}
/**
* Rearranges the array of 32-bit integers in ascending order.
* This is about 2-3x faster than Arrays.sort().
*
* @param a the array to be sorted
*/
static void sort(vector<int> &a) {
int BITS = 32; // each int is 32 bits
int R = 1 << BITS_PER_BYTE; // each bytes is between 0 and 255
int MASK = R - 1; // 0xFF
int w = BITS / BITS_PER_BYTE; // each int is 4 bytes
int n = a.size();
vector<int> aux(n);
for (int d = 0; d < w; d++) {
// compute frequency counts
vector<int> count(R+1);
for (int i = 0; i < n; i++) {
int c = (a[i] >> BITS_PER_BYTE * d) & MASK;
count[c + 1]++;
}
// compute cumulates
for (int r = 0; r < R; r++)
count[r + 1] += count[r];
// for most significant byte, 0x80-0xFF comes before 0x00-0x7F
if (d == w - 1) {
int shift1 = count[R] - count[R / 2];
int shift2 = count[R / 2];
for (int r = 0; r < R / 2; r++)
count[r] += shift1;
for (int r = R / 2; r < R; r++)
count[r] -= shift2;
}
// move data
for (int i = 0; i < n; i++) {
int c = (a[i] >> BITS_PER_BYTE * d) & MASK;
aux[count[c]++] = a[i];
}
// copy back
for (int i = 0; i < n; i++)
a[i] = aux[i];
}
}
private:
static int BITS_PER_BYTE;
};
int LSD::BITS_PER_BYTE = 8;
#endif //CH5_LSD_H