数据结构大作业——基数排序

#include <bits/stdc++.h>
using namespace std;
const int MAX = 10;
const int maxm = 1e5+10;
int len;
int num[maxm];
void print(){///output the array that is sorted
    cout<<num[0];
    for(int i = 1; i<len; i++)
        cout<<" "<<num[i];
    cout<<endl;
}
void RadixSortLSD()
{
    int buc[MAX];///bucket
    int maxn = 0;///the max number of the array
    int digitPosition = 1;///which one is being sorted
    for(int i = 0; i < len; i++){///initialize the max number
        maxn = max(maxn,num[i]);
    }
    while(maxn/digitPosition > 0){
        int digitCount[10] = {0};
        for(int i = 0; i < len; i++)
            digitCount[num[i]/digitPosition%10]++;///how many of the current bits are available
        for(int i = 1; i < 10; i++)
            digitCount[i] += digitCount[i-1];///prefix and
        for(int i = len - 1; i >= 0; i--)
            buc[--digitCount[num[i]/digitPosition%10]] = num[i];///reordering
        for(int i = 0; i < len; i++)
            num[i] = buc[i];///get the new array
        digitPosition *= 10;///move it
    }
}
int main()
{
    cin>>len;
    for(int i = 0; i<len; i++){
        cin>>num[i];
    }
    RadixSortLSD();
    print();
    return 0;
}

运行结果

这里写图片描述

猜你喜欢

转载自blog.csdn.net/mengzhongsharen/article/details/80812322