Radix Sort: Descending

僤鯓⒐⒋嵵緔 提交于 2019-12-06 15:37:22

The issue is trying to reverse the array on each pass, since radix sort preserves the order on equal values. After the third pass, 0705 ends up before 0099 (7 > 0). On the last pass, the most significant digits are 0, so the order kept, so b[0] = 0705, b[1] = 0099, then gets reversed to a[] = {..., 0099, 0705}.

Instead of reversing after each pass, reverse the indexes used for bucket by using 9 - digit. The changes are commented:

void RadixSort (int a[], int n){
int i, m=0, exp=1, b[MAX];
    for (i=0; i<n; i++)
        if (a[i]>m)
            m=a[i];
    while (m/exp>0)
    {
        int bucket[10]={0};
        for (i=0; i<n; i++)
            bucket[9-a[i]/exp%10]++;         // changed this line
        for (i=1; i<10; i++)
            bucket[i]+=bucket[i-1];
        for (i=n-1; i>=0; i--)
            b[--bucket[9-a[i]/exp%10]]=a[i]; // changed this line
        for (i=0; i<n;i++){
            a[i]=b[i];                       // changed this line
        }
        exp*=10;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!