#include <iostream>
#include <vector>
#include <string>
#include <algorithm> //计数排序
using namespace std;
int GetMax(int a[],int n)
{
int max=a[0];
for(int i=1;i<n;i++){
if(a[i]>max) max = a[i];
}
return max;
}
void countsort(int a[],int n)
{
int m = GetMax(a,n);
int b[m+1]={0};
for(int j=0;j<n;j++) b[a[j]]++;
for(int i=0,k=0;i<=m||k<n;i++)
{
while(b[i]>0){
a[k++] = i;
b[i]--;
}
}
}
int main()
{
int a[30] = {1,3,5,7,8,10,12,11,19,8,15,13,12,17,2,4,6,8,9,10,11,19,18,13,12,54,32,11,56,21};
cout<<"before sort"<<endl;
for(int i =0 ;i<30;i++) cout<<a[i]<<" ";
cout<<endl;
countsort(a,30);
for(int i=0;i<30;i++) cout<<a[i]<<" ";
/*int b[21]={0};
for(int i =0;i<25;i++) b[a[i]]++;
for(int j=0;j<=20;j++)
{
while(b[j]>0){
cout<<j<<" ";
b[j]--;
}
} */
return 0;
}
计数排序 C++代码
最新推荐文章于 2024-03-14 15:51:32 发布