- /*
- * 算法名称:计数排序
- * 算法思想:在最后排好序的序列中,第j个键码恰恰大于(j-1)个其它键码.
- * 比如:如果知道某个键码确实超过7个其它键码,而且没有两个键
- * 码相同,刚在排序之后对应的记录应当进入位置8.
- * 算法实现:
- * 通过维护一张辅助表count[1]...count[N],对于小于一个给定键
- * 码的键码个数进行计数,实现用键码K1,...Kn对记录R1,...,Rn排
- * 序. 算法结束时,count[j]+1确定记录Rj的最后位置.
- */
- #include <stdio.h>
- #include <time.h>
- #include <stdlib.h> /* for rand() and srand() */
- #define N 10 /* the number of elements */
- //@param:
- //array: to be sorted array.
- int *count_sort(int *array);
- //function:
- // initial the array with integer.
- //@param:
- //array: to be sorted array.
- void init_rand(int *array);
- //function: print the elements of the array.
- //@param:
- //array: to be sorted array.
- void print_array(int *array);
- int main(void)
- {
- int array[N];
- init_rand(array);
- printf("The array has been initialed as follows:/n");
- print_array(array);
- count_sort(array);
- printf("After count sort:/n");
- print_array(array);
- return 0;
- }//main()
- void init_rand(int *array)
- {
- int i;
- srand((unsigned)time(NULL));
- for (i = 0; i < N; i++)
- {
- array[i] = rand() % 900 + 100; /* initialize the array between 100 and 999 */
- }//for
- }//init_rand()
- void print_array(int *array)
- {
- int i;
- for (i = 0; i < N; i++)
- {
- printf("%d/t", array[i]);
- }//for
- printf("/n");
- }//print_array()
- int *count_sort(int *array)
- {
- int i,j;
- int count[N] = {0};
- int temp[N] = {0};
- for (i = 1; i < N; i++)
- {
- for (j = 0; j < i; j++)
- {
- array[i] < array[j] ? count[j]++ : count[i]++;
- }//for
- }//for
- printf("Now, the elements' value of count are as follows:/n");
- print_array(count);
- for (i = 0; i < N; i++)
- {
- temp[i] = array[i];
- }//for
- for (i = 0; i < N; i++)
- {
- array[count[i]] = temp[i];
- }//for
- return array;
- }//count_sort()
- //运行情况;
-
- lee@Lee:~/MyProject/sort/count_sort$ ./count_sort
- The array has been initialed as follows:
- 418 292 332 357 709 779 336 103 503 802
- Now, the elements' value of count are as follows:
- 5 1 2 4 7 8 3 0 6 9
- After count sort:
- 103 292 332 336 357 418 503 709 779 802
- --------------------------------------------------------------------
- lee@Lee:~/MyProject/sort/count_sort$ ./count_sort
- The array has been initialed as follows:
- 486 158 181 688 235 687 566 420 185 747
- Now, the elements' value of count are as follows:
- 5 0 1 8 3 7 6 4 2 9
- After count sort:
- 158 181 185 235 420 486 566 687 688 747