Input: A[1...n], each 0<A[i]<=k
Output: B[1...n] = sorting of A
Auxiliary: C[1...k]
Restricts:
1. each element little than a const "k"
2. the element should be integer
3. the range of the elements shoud not be so large (or it will cost more than nlgn and waste more space)
The idea about this algorithm:
About the arrary C, C[i] store the information about how many numbers in the array A which less than or equal "i".
To finish this task:
Step1: traverse the array A and C[A[i]]++. Such as A[0]=10, then the C[10]++.
Step2: use prefix sum to change the value in array C. After the transform C[i] give number of keys less than or equal i.
#include <iostream>
using namespace std;
int * CountSort(int* A,int p,int q,int bound){
int size=q-p+1;
int * C=new int[bound+1];
int * B=new int[size];
for(int i=0;i<=bound;i++){
C[i]=0;
}
for(int i=0;i<size;i++){
C[A[p+i]]++;
}
for(int i=1;i<=bound;i++){
C[i]+=C[i-1];
}
for(int j=size-1;j>=0;j--){
B[C[A[p+j]]-1]=A[p+j];
C[A[p+j]]--;
}
return B;
}
int main(){
int Arr[15]={1,4,3,6,2,6,3,5,4,9,2,4,6,7,3};
int *Res;
Res=CountSort(Arr,0,14,9);
for(int i=0;i<14;i++){
cout<<Res[i]<<" ";
}
return 0;
}
Advantage of Counting Sort: The Time Complexity is O(k+n), if k=O(n) the Time will be O(n), which beat all comparsion sort algorithm.
Disadvantage: It cost so many space. It can be represented as O(k).