基数使用队列排序

时间:2014-05-17 18:11:21

标签: c++ radix-sort

我的程序采用未排序的数组,然后使用基数排序进行排序。基数排序使用一个队列数组,每个可能的数字一个,然后遍历每个数字并将其放回到数组中,直到所有位置值都运行,从而对数组进行排序。现在它排序不正常,它吐出不正确的值,我相信它与我如何将它们放回数组有关。任何帮助将不胜感激,谢谢。

#include <iostream>
#include <queue>
#include <ctime>
#include <cstdlib>
using namespace std;

int *radixSort(int q[]);

int main() {
const int MAX=1000;
int radix[MAX], *sortedRadix;
int seed =time(0);
srand(seed);


//fill array with random #s
for (int i=0;i<MAX;i++){
    int num=0+rand()%MAX;
    radix[i]=num;
}
//print unsorted
for (int j=0;j<MAX;j++)
    cout << radix[j] << " ";
cout << endl << endl;
//radix sort
sortedRadix=radixSort(radix);
//print sorted
for (int j=0;j<MAX;j++)
    cout << sortedRadix[j] << " ";

cout << endl <<endl;
cout<<"flag";


return 0;
}

int *radixSort(int q[]) {
queue<int> bins[10]; //one array per possible digit
int maxDigits=3; //holds amount of digits in largest number
int currentDigit=1; //right most digit
int a[1000]; //holds numbers during sort

while (currentDigit <= maxDigits) {
    for(int i=0; i<1000; i++){ //loop through whole array
        int num = q[i]; //set to current value of array position
        int digitValue = static_cast<int>(num/currentDigit)%10; //get the decimal digit at current digit
        bins[digitValue].push(num); //put digits in corresponding bins
    }
    //Transfer results of bins back into main array
    for (int j=0; j<1000; j++){
        for(int k=0;k<10;k++){ //loop through all bins
            while (!bins[k].empty()){ //push all elements in bin[k] until empty to a
                int temp=bins[k].front();
                a[j]=temp;
                bins[k].pop();
            }
        }
    }
currentDigit++;
}
return a;
}

0 个答案:

没有答案