It is suitable for sorting integers and smaller values.
When the input element is n integers between 0 and K, its running time is (N+K). Counting sorting is not a comparative sorting, and the sorting speed is faster than any comparative sorting algorithm.
Because the Array Used for countingCThe length of the array depends on the range of data in the array to be sorted (equal to the difference between the maximum and minimum values of the array to be sorted plus 1), which makes counting sorting an array with a large data range, requires a lot of time and memory. For example, counting sorting is the best algorithm for sorting numbers between 0 and 100, but it is not suitable for sorting names in alphabetical order. However, counting sorting can be used in the base Sorting Algorithm to sort arrays with a large data range.
The algorithm steps are as follows:
- Find the largest and smallest elements in the array to be sorted
- Each value in the statistics array isINumber of times the element appears, saved to the arrayCTheIItem
- Accumulate all counts (fromCStart with the first element, and add each item to the previous one)
- Reverse filling of the target array: add each elementIPlace the column in the New ArrayC (I)Item.C (I)Minus 1
# Include <stdio. h> # include <stdlib. h> # include <time. h> # include <string. h> // int arr [] = {,}; void print_arr (int * arr, int N) {int I; for (I = 0; I <n; I ++) {If (! I) {printf ("% d", arr [I]);} else {printf ("% d", arr [I]);} printf ("\ n");}/*** n is the length of the array, and Max is the range of the number to be sorted. */Void count_sort (int * ini_arr, int * sorted_arr, int N, int max) {int * cnt_arr = (int *) malloc (sizeof (INT) * max ); for (INT I = 0; I <Max; I ++) {cnt_arr [I] = 0 ;}for (INT I = 0; I <n; I ++) {cnt_arr [ini_arr [I] ++;} For (Int J = 1; j <Max; j ++) cnt_arr [J] + = cnt_arr [J-1]; // cnt_arr Save the subscript. stability for repeated elements (int K = n-1; k> = 0; k --) {sorted_arr [cnt_arr [ini_arr [k]-1] = ini_arr [k]; cnt_arr [ini_arr [k] --;} Free (cnt_arr ); // release resources} int main () {int n = 20; int max = 10; int * dest_arr = (int *) malloc (sizeof (INT) * n ); int * arr = (int *) malloc (sizeof (INT) * n); srand (time (0); For (INT I = 0; I <N; I ++) {arr [I] = rand () % Max;} print_arr (ARR, n); count_sort (ARR, dest_arr, N, 10); print_arr (dest_arr, n); Return 0 ;}