-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdemo_radix_sort_1.c
109 lines (85 loc) · 2.22 KB
/
demo_radix_sort_1.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#define NUM_OF_POS(a, pval) ((a) / pval) % 10
void dump(int *arr, int size) {
int idx;
for (idx = 0; idx < size; idx++) {
printf("%d\n", arr[idx]);
}
}
/**
select (x / pow(10, 0)) % 10;
123 12341 124 236 128 1112313129 98 9 8989
3 1 4 6 8 9 8 9 9
select (x / pow(10, 1)) % 10;
123 12341 124 236 128 1112313129 98 9 8989
2 4 2 3 2 2 9 0 8
select (x / pow(10, 2)) % 10;
123 12341 124 236 128 1112313129 98 9 8989
1 3 1 2 1 1 0 0 9
select (x / pow(10, 3)) % 10;
123 12341 124 236 128 1112313129 98 9 8989
0 2 0 0 0 3 0 0 8
select (x / pow(10, 4)) % 10;
123 12341 124 236 128 1112313129 98 9 8989
0 0 0 0 0 1 0 0 0
select (x / pow(10, 5)) % 10;
123 12341 124 236 128 1112313129 98 9 8989
0 0 0 0 0 3 0 0 0
.....
*/
void radix_sort(int a[], int size, int num_count) {
int count[10] = {0}; // 计数
int *pres = NULL;
int i = 0;
int j = 0;
int pval = 0;
int index = 0;
int break_flg = 0;
pres = (int *)malloc(sizeof(int) * size);
assert(pres != NULL);
for (i = 0; i < num_count; i++) {
memset(count, 0, sizeof(int) * 10);
// 求当前的基数
pval = pow(10, i);
// 计数
for (j = 0; j < size; j++) {
index = NUM_OF_POS(a[j], pval);
count[index]++;
}
if (count[0] == 9) {
break_flg++;
}
if (break_flg >= 2) {
printf("\n %i", i);
break;
}
// 累加
for (j = 1; j < 10; j++) {
count[j] += count[j - 1];
}
// 排序必须从后往前,否则不是稳定排序
for (j = size - 1; j >= 0; j--) {
index = NUM_OF_POS(a[j], pval);
pres[count[index] - 1] = a[j];
count[index]--;
}
// 本轮排序好的,拷贝到a中
memcpy(a, pres, sizeof(int) * size);
}
return;
}
void radix_sort_test() {
int a[10] = {123, 12341, 12341, 124, 236, 128, 1112313129, 98, 9, 8989};
printf("\n radix sort test .... ");
radix_sort(a, 10, 10);
dump(a, 10);
return;
}
int main() {
radix_sort_test();
return 0;
}