-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.cpp
58 lines (52 loc) · 1.09 KB
/
radix_sort.cpp
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
#include <cstdio>
#include <deque>
#include <queue>
#include <stack>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <bitset>
#include <list>
#include <set>
#include <map>
using namespace std;
// is used to sort the number by digit because we can use count sort
// on digit so complexity will be O(n).
// sorting start from least significant digit.
const int N = 100010;
const int D = 10;
int a[N], b[N], cnt[D];
// counting sort based on rank.
void countSort(int n, int bit) {
memset(cnt, 0, sizeof(cnt));
for(int i = 0; i < n; i++) {
int dz = (a[i] / bit) % 10;
cnt[dz]++;
}
for(int i = 1; i < D; i++) {
cnt[i] += cnt[i - 1];
}
for(int i = n - 1; i >= 0; i--) {
int dz = (a[i] / bit) % 10;
b[cnt[dz] - 1] = a[i];
cnt[dz]--;
}
memcpy(a, b, n * sizeof(int));
}
int main() {
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d", a + i);
}
int bit = 1;
for(int i = 1; i < D; i++) {
countSort(n, bit);
bit *= 10;
}
for(int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
}