基数排序

#include <iostream>
using namespace std;
int maxbit(int data[],int n) //求数据的最大位数
{
int i,p,max=0;
int *temp;temp=new int[n];
for(i=0;i<n;i++)temp[i]=data[i];
for(i=0;i<n;i++)
{
p
=1;
while(temp[i]/10>0)
{
p
++;temp[i]=temp[i]/10;
}
if(p>max)max=p;
}
delete[]temp;
return max;
}
void radixsort(int data[],int n) //基数排序
{
int *temp;temp=new int[n];
int i,j,k;
int count[10];
int radix=1;
for(i=radix;i<=maxbit(data,n);i++)
{
for(j=0;j<10;j++)count[j]=0;
for(j=0;j<n;j++)
{
k
=(data[j]/radix)%10;
count[k]
++;
}
for(j=1;j<10;j++) //这一步重要
count[j]+=count[j-1];
for(j=n-1;j>=0;j--) //从后往前进行
{
k
=(data[j]/radix)%10;
count[k]
--;
temp[count[k]]
=data[j];
}
for(j=0;j<n;j++)
data[j]
=temp[j];
radix
=radix*10;
}
delete[]temp;
}
void main()
{
int data[]={73,22,593,43,155,14,228,65,39,81};
radixsort(data,
10);
for (int i=0;i<10;i++)
cout
<<data[i]<<" ";
cout
<<endl;
}

  

posted on 2011-08-22 15:05  sysu_mjc  阅读(175)  评论(0编辑  收藏  举报

导航