基数排序

//基数排序
#include<iostream.h>
void funCount(int *count,int* a,int length,int num)//对应位上数字的个数
{
    for (int i=0;i<length;i++)
    {
        int x=a[i];
        for (int j=2;j<=num;j++)
        {
            x=x/10;
        }
        x=x%10;
        count[x]++;
    }
}
void funIndex(int* count,int* index)//对应位上数字开始存放的位置
{
    for (int i=1;i<10;i++)
    {
        index[i]=index[i-1]+count[i-1];
    }
}
void funSort(int* a,int* b,int* index,int length,int num)//向辅助数组上放数字
{
    for (int i=0;i<length;i++)
    {
        int x=a[i];
        for (int j=2;j<=num;j++)
        {
            x=x/10;
        }
        x=x%10;
        b[index[x]++]=a[i];
    }
}
int fun(int *a,int length)//返回数字中最长的长度
{
    int max=a[0];
    for (int i=0;i<19;i++)
    {
        if (max<a[i])
        {
            max=a[i];
        } 
    }
    int x=0;
    while (max!=0)
    {
        max=max/10;
        x++;
    }
    return x;
}
void main()
{
    int a[]={3,36,58,12,62,59,26,39,78,97,31,50,1254,70,88,64,34,127};
    int b[18];
    int length=fun(a,18);
    int *temp1=a;
    int *temp2=b;
    for(int i=1;i<=length;i++)
    {
        int count[10]={0};//存储每位的对应的个数
        int index[10]={0};//开始存放的下标
        funCount(count,temp1,18,i);
        funIndex(count,index);
        funSort(temp1,temp2,index,18,i);
        int *temp=temp1;//交换一下指针的指向
        temp1=temp2;
        temp2=temp;
    }
    for (i=0;i<18;i++)
    {
        cout<<b[i]<<"  ";
    }
    cout<<endl;
    
}
原文地址:https://www.cnblogs.com/GoAhead/p/2673570.html