计数排序

//元素只能为正整数
#include <iostream>
using namespace std;

int Max(int *a,int length)
{
int temp=-1000;
for (int i=0;i<length;i++)
if (temp<a[i])
temp=a[i];
return temp;
}

void counting_sort(int *a,int *b,int k,int length)
{
int *c;
c=(int*)malloc(sizeof(int)*(k+1));
for (int i=0;i<=k;i++)
c[i]=0;

for (int j=0;j<length;j++)
c[a[j]]=c[a[j]]+1;

for (int i=1;i<=k;i++)
c[i]=c[i]+c[i-1];

for (int j=length-1;j>=0;j--)
{
b[c[a[j]]-1]=a[j];
c[a[j]]=c[a[j]]-1;
}
free(c);
}

int main()
{
int a[]={2,15,1,3,21,32,1,3,7};
int length=sizeof(a)/sizeof(int);
int *b;
b=new int[length];
counting_sort(a,b,Max(a,length),length);

for (int i=0;i<length;i++)
cout<<b[i]<<"";
cout<<endl;

system("pause");
free(b);
return 0;
}
原文地址:https://www.cnblogs.com/tiandsp/p/2358160.html