You can comprehend this problem from two different points of view.
Case 1: For an element x in an array, to check how many elements is less than x, after we got that message, we can put x to the right position. For example, if we have 17 elements less than x, the right position for x is 18.
Case 2: You can also comprehend this problem from the other point of view. If an element values vi appears x times, you should put x to the position vi in the array C.
When you finish the counting, rearrange the array A according array C.
Here I only implement this algorithms according case 2, because it has a smaller space complexity, just as follow:
1. Before you count the array, you should know the maximum and minimum first.
2. Create a new array C, its length is maximum-minimum+1.
3. Counting the element in the array, if the same element appears x times, then put x to the array C and the position is the element’s value.
4. Loop through array C and rearrange the array A, if an element in array C have a value C[i], that means from the current position you want to process to the next C[i] position of array A, they have the same value i.
The time complexity of the count sort is O(n+k),so if the k is not too big, you will gain a higher efficiency.
The following is the implement of counting sort by java.
public int[] countSort(int[] A, int max,int min){
int[] C = new int[max-min+1];
for(int i = 0;i < max-min;i++) {
C[i] = 0;
}
for(int i = 0;i < A.length;i++){
C[A[i]-min] = C[A[i]-min]+1;
}
int index = 0;
for(int i = 0;i < C.length;i++){
while(C[i] > 0){
A[index] = i+min;
index++;
C[i]--;
}
}
return A;
}