首先计算数据的范围,然后为该范围内可能出现的元素建立一系列对应的计数器再重新扫描一遍同时根据扫描到的元素自增相应的计数器,最后把计数器内容读出来写回原数组。 int counterSort(int *data, int size) { if (data == NULL || size <= 0) return -1; int min = *data, max = *data; int *data_p = data + 1, *data_endp = data + size; while(data_p != data_endp) { if (*data_p < min) min = *data_p; if (*data_p > max) max = *data_p; data_p++; } int *counter = (int*)malloc(sizeof(int) * (max - min + 1)); if (counter == NULL) return -2; memset(counter, 0, sizeof(int) * (max - min + 1)); data_p = data; while(data_p != data_endp) { (*(counter + *data_p - min))++; data_p++; } int i; data_p = data; for (i = 0; i < max - min + 1; i++) { if (*(counter + i) > 0) { int j; for (j = 0; j < *(counter + i); j++) *data_p++ = i + min; } } free(counter); return 0; }