The count sort assumes that each of the N input elements is an integer between 0 and K, and K is the largest element in the N number. When K=o (n), the run time of the count sort is θ (n). The basic idea of counting sorting is to count the number of elements that are less than or equal to x for each element x in n input elements, and to determine the final position of x in the output array based on the number of X. This process requires the introduction of two secondary storage spaces, the B[1...N of the results], to determine the array of the number of each element C[0...K]. The specific steps of the algorithm are as follows:
(1) Determine the value of K based on the value of the element in the input array A and initialize c[1....k]= 0;
(2) Iterate through the elements in the input array A, determine the number of occurrences of each element, and store the number of occurrences of the first element in a c[a[i]], and then c[i]=c[i]+c[i-1], in C to determine that each element in a is preceded by multiple elements;
(3) Reverse-iterate through the elements in array A, find the number of occurrences in a in C, and determine its position in the result array B, and then reduce its corresponding number of times in C by 1.
#include <iostream>using namespace std;void count_sort (int a[], int b[], int k, int length) {int I, J;//each element i n A between 0 and K [0,k],total k+1 elements;//int *c = new Int[k + 1];int *c = (int*) malloc (sizeof (int) * (k+1)); memset (c, 0, (k+1) *sizeof (int));//c[i] Now contains the number of element equal to i;for (i = 0; i < length; ++i) c[a[i]] = c[a[i ]] + 1;//c[i] Now contains the number of elements less than or equal to i;for (j = 1; j <= K; ++j) c[j] = C[j] + c[j-1 ];for (i = length-1; I >= 0; i--) {b[c[a[i]]-1] = A[i];c[a[i] [c[a[i]]-1;} A[i] means the INPUT element, C[a[i]] [] Indicates the number of occurrences, then b[c[a[i]]-1] means the position of the a[i] in the B array, and then c[a[i]] should be reduced by the number of times}int main () {int a[] = {5, 6, 9, 5, 0, 8, 2, 1, 6, 9, 8, 3, 4, 8, 6, 7, 6, 3, 3, 3, 3, 3, 8, 8, 8,11};int len = sizeof (a)/sizeof (int); cout << Len <& Lt Endl;int B[26];count_sort (A, B, one, Len); for (int i = 0; i < len;i++) cout << b[i] << "";}
Introduction to Algorithms--------------counting sort and cardinal sort