Counting sort assumes that each of then input elements is an integer in the range 0 to k, for some integer k. When k =O(n), the sort runs in Θ(n) time.
The basic idea of counting sort is to determine, for each input elementx, the number of elements less than x. This information can be used to place element x directly into its position in the output array. For example, if there are 17 elements less thanx, then x belongs in output position 18. This scheme must be modified slightly to handle the situation in which several elements have the same value, since we don't want to put them all in the same position.
In the code for counting sort, we assume that the input is an arrayA[1 ‥ n], and thus length[A] =n. We require two other arrays: the array B[1 ‥n] holds the sorted output, and the arrayC[0 ‥ k] provides temporary working storage.
COUNTING-SORT(A, B, k) 1 for i ← 0 to k 2 do C[i] ← 0 3 for j ← 1 to length[A] 4 do C[A[j]] ← C[A[j]] + 1 5 ▹ C[i] now contains the number of elements equal to i. 6 for i ← 1 to k 7 do C[i] ← C[i] + C[i - 1] 8 ▹ C[i] now contains the number of elements less than or equal to i. 9 for j ← length[A] downto 1 10 do B[C[A[j]]] ← A[j] 11 C[A[j]] ← C[A[j]] - 1 代码,VS2008编译通过
#include<iostream> #include<time.h> using namespace std;
void initArray(int arr[], int n, int top){ srand(time(NULL)); for(int i=0; i<n; i++){ arr[i] = rand()%top; } }
void printArray(int arr[], int n){ for(int i=0; i<n; i++){ cout <<arr[i]<<" "; } cout<<endl; }
void countSort(int arr[], int n, int max){//max for the number one larger than max int* B = (int*) malloc(n*sizeof(int));//store the result int * C = (int*) malloc(max*sizeof(int));//store the counter memset(C,0,max*sizeof(int)); for(int i=0; i<n; i++){//counter number C[arr[i]]++; } //counter <= for(int i=1; i<max;i++){ C[i] += C[i-1]; }
for(int i=n-1; i>0; i--){ B[C[arr[i]]-1] = arr[i]; C[arr[i]]--;//handle for equal } memcpy(arr,B,n*sizeof(int)); free(B); free(C);
}
void main(){ const int AD = 20; int arr[AD]; initArray(arr,AD,400); printArray(arr,AD);
countSort(arr,AD,400); printArray(arr,AD); exit(0); }
欢迎批评指正,共同进步