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
| #include <stdio.h>
#include <stdlib.h>
#define ARRSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
void CountingSort(int elements[], int len)
{
int max, min, i, j;
//寻找最大值和最小值
max = elements[0];
min = elements[0];
for (i = 0; i < len; i++)
{
if (max < elements[i])
max = elements[i];
if (min > elements[i])
min = elements[i];
}
//base的作用是节省内存,假设最小值min为1000,最大值为3000,所以我们最多只需要2001个大小的数组,而不用去用0-3000个空间浪费内存
int base = 0 - min;
int space = max - min + 1;
int *bucket = (int *)malloc(sizeof(int) * space);
//初始化容器中的数值
for (i = 0; i < space; i++)
bucket[i] = 0;
//以elements[i]作为bucket的下标存放数据
for (i = 0; i < len; i++)
bucket[elements[i]]++;
//将有序的数值还原
j = 0, i = 0;
while (j < len)
{
//当i大于0时,可能有多个数需要还原,所以只当他为0时++
if (bucket[i] != 0)
{
elements[j++] = i - base;
bucket[i]--;
}
else
i++;
}
free(bucket);
}
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);
CountingSort(elems, len);
for (int i = 0; i < len; i++)
printf("%4d", elems[i]);
printf("\n");
return 0;
}
|