计数排序
As the original array is A, without sorting, we define twoadditional arrays B and C. C is used as a storage which helps toclarify the position of each number of array A in array B.
Firstly, we use C to store the frequency of each number of arrayA appears. Then we plus each number and the onesbefore it, useing the results to refillin each position of array C.The index of array Cis just the value of arrayA, and the the pointing value ofthe index in array C implies the final position of each number ofarray A in array B.
Counting sort is stable, and usually applies in the situationthat we can be sure the value of the max number. It has somelimitations, for example, the numbers to be sorted must benonegtive.
Following is one implementation of counting sort algorithm,using Java.
public void Counting_Sort(int[] A, max){
int len= A.length;
int[] B = new int[len]; //B is the finalarray
int[] C = new int[max + 1];// C is thestorage, with each number initialed with 0
// the frequency of the appearence of eachnumber in array A
for (int i = 0; i < n; i++){
C[A[i]] = C[A[i]] + 1;
}
// the number thatsatisifying the condition of i <=max;
// each number plus with the ones beforeit
for (int i = 1; i <= max; i++){
C[i] = C[i] + C[i - 1];
}
// put the value of A into the right positionof B
for (i = n - 1; i> 0; i --){
B[C[A[i]]] = A[i];
C[A[i]] = C[A[i]] - 1; // encounting the same value
}
}