Counting sorting, which is suitable for the case where the value span is relatively small, that is, the maximum value in the array minus the minimum value is as small as possible. When there are many array elements, the efficiency of counting sorting is relatively high, in addition, the basic friend stability of the counting sorting algorithm.
The time complexity of counting sorting is O (n). Counting sorting is the best algorithm used to sort numbers between 0 and 100.
The algorithm steps are as follows:
1. Find the largest and smallest elements in the array to be sorted
2. count the number of times each element with a value of I appears in the array, and store the I entry of array C
3. accumulate all counts (starting from the first element in C and adding each item to the previous one)
4. Backward filling of the target array: place each element I in the item C (I) of the new array, and subtract 1 from each element.
The following is a C language implementation code:
# Include <stdio. h> # include <stdlib. h> # include <time. h>/* run this program using the console pauser or add your own getch, system ("pause") or input loop */void print_arry (int * arr, int N) {int I; for (I = 0; I <n; I ++) {printf ("% d", arr [I]);} printf ("\ n");} void count_sort (int * arr, int * sorted_arr, int N) {int * count_arr = (int *) malloc (sizeof (INT) * 100); int I; // The initialization count array for (I = 0; I <100; I ++) count_arr [I] = 0; // count the number of I for (I = 0; I <n; I ++) count_arr [arr [I] ++; // accumulate all counts for (I = 1; I <100; I ++) count_arr [I] + = count_arr [I-1]; // reversely records the source array (ensuring stability) and fills it in the first array based on the corresponding values in the count array (I = N; I> 0; I --) {sorted_arr [count_arr [arr [I-1]-1] = arr [I-1]; count_arr [arr [I-1] --;} Free (count_arr);} int main () {int N, I; printf ("Size of the array to be sorted n ="); scanf ("% d", & N); int * arr = (int *) malloc (sizeof (INT) * n); int * sorted_arr = (int *) malloc (siz EOF (INT) * n); srand (time (0); for (I = 0; I <n; I ++) {arr [I] = rand () % 100;} printf ("the randomly generated value is 0 ~ Array of 99... \ n "); printf (" initialization array: "); print_arry (ARR, n); count_sort (ARR, sorted_arr, n); printf (" sorted array: "); print_arry (sorted_arr, n); Return 0; System (" pause ");}