The decision tree model shows that the next term to compare the worst cases is to compare the NLGN times, not the linear sort. So, in the introduction of the algorithm, several linear sorts are proposed, in which the counting sort is one kind. The following summarizes the principle of counting sorting:
Assume that each element in N input elements is an integer within [0,.., K]. Set the input array to a[n]; the output array is b[n]; The temporary storage array is c[k]. The algorithm is as follows:
1. Place all elements in C[k] 0.
2. Statistics A contains the number of element I (i={0,..., k-1}) and is stored in c[i].
3. Count the number of elements in a that are less than or equal to i (i={0,..., k-1}) and stored in c[i].
4. Starting with n-1, the position specified in B, which is equal to the element of I in A, B is a well-ordered output. Because in 2 and 3 we already know the number of elements that are less than or equal to I, so here we just need to store I on B[c[i] [], and subtract the c[i] by 1, repeating this process until all the elements in a are stored in B.
The C language is implemented as follows:
#include <stdio.h> #include <stdlib.h> #include <time.h>void countsort (int a[],int b[],int n,int k) { int i,*c; C=malloc (k*sizeof (int)); for (i=0;i<k;i++) c[i]=0; for (i=0;i<n;i++) c[a[i]]++; Count the number of a[i in the array a], and place the a[i] value in C[a[i]]. for (i=1;i<k;i++) c[i]+=c[i-1]; Calculate how much of a is less than or equal to A[i], and store it in C[a[i]]. for (i=n;i>0;i--) b[--c[a[i-1]]]=a[i-1]; Store the value of a[i-1] in B[--c[a[i-1]]]. Free (C);}
This article is from the "stupid Donkey on the tree" blog, please be sure to keep this source http://xu2015.blog.51cto.com/10019822/1675911
Understanding and code implementation of counting sorting