稳定,O(n)
#include <stdio.h>
#include <stdlib.h>
int Max(int a[], int n) {
int max_num = a[0];
int i = 1;
while (i < n) {
if (max_num < a[i]) {
max_num = a[i];
}
++i;
}
return max_num;
}
void CountSort(int a[], int b[], int n) {
int i = 0;
int max_num = Max(a, n);
int* temp = (int*)malloc(sizeof(int) * (max_num + 1));
if (NULL == temp) {
printf("malloc error! temp\n");
return;
}
for (i = 0; i < max_num + 1; ++i) {
temp[i] = 0;
}
for (i = 0; i < n; ++i) {
temp[a[i]]++; //把原数组值作为下标存储到临时数组中
}
for (i = 1; i <= max_num; ++i) { //一定是小于max_num,因为c数组下标最大到max
temp[i] += temp[i-1]; //是为了求得a[i]在新的数组中的顺序
}
for (i = n - 1; i >= 0; --i) { //这样能保证排序后的结果稳定,即相同的数相对顺序排序后没有发生变化
b[temp[a[i]] - 1] = a[i]; //把相应值按顺序放到结果数组b中
--temp[a[i]];
}
free(temp);
}
int main() {
int i = 0;
int a[] = {1, 2, 3, 5, 4, 78, 56, 9, 87, 10};
int* result = (int*)malloc(sizeof(int) * sizeof(a)/sizeof(a[0]));
if (NULL == result) {
printf("malloc error! result\n");
return -1;
}
printf("排序前: ");
for (i = 0; i < sizeof(a)/sizeof(a[0]); i++)
printf("%d ", a[i]);
printf("\n");
CountSort(a, result, sizeof(a)/sizeof(a[0]));
printf("排序后: ");
for (i = 0; i < sizeof(a)/sizeof(a[0]); i++)
printf("%d ",result[i]);
printf("\n");
return 0;
}