其他分享
首页 > 其他分享> > 计数排序

计数排序

作者:互联网

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef int type;
 5 
 6 void counting_sort(const type *arr, int size, type *target, int k) {
 7     int *count = (int *) malloc(sizeof(int) * (k + 1));
 8     for (int i = 0; i <= k; ++i) {
 9         *(count + i) = 0;
10     }
11     for (int i = 0; i < size; ++i) {
12         ++*(count + *(arr + i));
13     }
14     for (int i = 1; i <= k; ++i) {
15         *(count + i) += *(count + i - 1);
16     }
17     for (int i = size - 1; i >= 0; --i) {
18         *(target + *(count + *(arr + i)) - 1) = *(arr + i);
19         --*(count + *(arr + i));
20     }
21     free(count);
22 }
23 
24 int main() {
25     type arr[] = {3, 2, 9, 4, 1};
26     const int size = sizeof(arr) / sizeof(type);
27     type target[size];
28     int k = 9;
29 
30     counting_sort(arr, size, target, k);
31     for (int i = 0; i < size; ++i) {
32         printf("%d\n", target[i]);
33     }
34     return 0;
35 }

 

标签:count,arr,target,int,计数,排序,type,size
来源: https://www.cnblogs.com/zhangshiyu/p/16439032.html