计数排序,白天手机看维基百科看到的. 对付数据跨度小的 int 型数据,的确很快.代码,很直观. /* count_sort-11-03-21-19.01.c -- 计数排序 */ #include <stdio.h> #include <stdlib.h> #define SIZE (10) int main (void) ; int countSort (int * const array, const int size) ; void printResult (const int * const array, const int size) ; int main (void) { int array[SIZE] = {7, 22, 4, 3, 0, 0, 9, 11, 8, 15} ; int size = SIZE ; printResult (array, size) ; countSort (array, size) ; printResult (array, size) ; return 0 ; } int countSort (int * const array, const int size) { int * count ; int * result; int min, max ; int range, i ; min = max = array[0] ; for (i = 0; i < size; i++) { if (array[i] < min) min = array[i] ; else if (array[i] > max) max = array[i] ; } range = max - min + 1 ; count = (int *) malloc (sizeof (int) * range) ; if (NULL == count) return 0 ; result = (int *) malloc (sizeof (int) * size) ; if (NULL == result) { free (count) ; return 0 ; } for (i = 0; i < range; i++) count[i] = 0 ; for (i = 0; i < size; i++) count[array[i] - min]++ ; for (i = 1; i < range; i++) count[i] += count[i - 1] ; for (i = size - 1; i >= 0; i--) result[--temp[array[i] - min]] = array[i] ; for (i = 0; i < size; i++) array[i] = result[i] ; free (count) ; free (result) ; return 1 ; } void printResult (const int * const array, const int size) { int i ; for (i = 0; i < size; i++) printf ("%-4d", array[i]) ; putchar ('/n') ; }