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
| #include <stdio.h>
#include <stdlib.h>
#define ARRSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
#define BUCKET_CAPACITY 30 //单个桶的容量,根据情况进行修改
#define BUCKET_COUNT 10 //桶的数量(0-9)我们只需要10个桶
typedef struct Bucket
{
int values[BUCKET_CAPACITY];
int size;
} Bucket, *PBucket;
void RadixSort(int elements[], int len)
{
int max = elements[0];
int i, j, k;
//寻找序列中的最大值
for (i = 0; i < len; i++)
{
if (max < elements[i])
max = elements[i];
}
//计算位数
int maxDigits = 0;
while (max != 0)
{
max /= 10;
maxDigits++;
}
//生成桶
PBucket buckets = (PBucket)malloc(sizeof(Bucket) * BUCKET_COUNT);
int radix = 10; //每次模的基数
for (i = 0; i < maxDigits; i++, radix *= 10)
{
//先清空桶
for (j = 0; j < BUCKET_COUNT; j++)
buckets[j].size = 0;
//进桶
for (j = 0; j < len; j++)
{
//以位数为基数,放入相应的桶
int n = (elements[j] % radix) / (radix / 10);
buckets[n].values[buckets[n].size++] = elements[j];
}
//从桶里放回排序过的数
int index = 0;
for (j = 0; j < BUCKET_COUNT; j++)
{
if (buckets[j].size < 1)
continue;
for (k = 0; k < buckets[j].size; k++)
{
elements[index++] = buckets[j].values[k];
}
}
}
free(buckets);
}
int main(int argc, char const *argv[])
{
int elems[] = {3, 4, 2, 1, 5, 9, 2, 1, 0, 22, 33, 5, 112, 11, 22, 55, 22, 61, 97};
int len = ARRSIZE(elems);
RadixSort(elems, len);
for (int i = 0; i < len; i++)
printf("%4d", elems[i]);
printf("\n");
return 0;
}
|