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).
本文深入探讨了计数排序算法的核心概念、步骤实现及其优势。通过实例演示了如何利用辅助数组C来统计数组A中各元素出现次数,并通过前缀和优化更新数组C,最终实现数组A的排序。重点强调了计数排序的时间复杂度为O(k+n),当k接近n时,其效率远超比较排序算法。

被折叠的 条评论
为什么被折叠?



