class CountingSort
{
private:
int *arr;//待排序数组
int *count;
int *result;
int length;//数组长度
int max;//最大元素
public:
//构造函数
CountingSort(int length)
{
max=-1;
this->length=length;
arr=new int[length+1];
result=new int[length+1];
}
//输入
void input()
{
int i=1;
while(i<=length)
{
cin>>arr[i];
if(arr[i]>max)//记录数组中最大值
{
max=arr[i];
}
i++;
}
count=new int[max+1];
}
//计数排序
void countingSort()
{
//初始化每一个元素的数量为0
for(int i=0;i<=max;i++)
{
count[i]=0;
}
//记录数组中出现的元素的个数
for(int j=1;j<=length;j++)
{
count[arr[j]]++;
}
//计算小于等于1:MAX每个元素的元素数量
for(int k=1;k<=max;k++)
{
count[k]=count[k]+count[k-1];
}
//根据count[],将每个元素插入到相应的位置
for(int m=1;m<=length;m++)
{
result[count[arr[m]]]=arr[m];
count[arr[m]]--;
}
}
//打印排序后结果
void display()
{
int i=1;
while(i<=length)
{
cout<<result[i++]<<" ";
}
}
};
void main()
{
CountingSort test(10);//数组有10个元素
test.input();//输入10个元素
test.countingSort();//计数排序
test.display();//打印结果
}