Radix使用队列排序整数C ++

时间:2016-11-07 00:53:47

标签: c++ sorting queue radix-sort

我一直试图在我的算法(3位数字)中解决这个错误,这个错误只通过n位数的最低有效数字(数字的最右边的数字)排序。我试图从最右边的数字开始工作,向左移动。我尝试的解决方案之一是从左到右工作,因为它是反向排序,虽然它改进了排序,但它仍然是不正确的。非常感谢任何帮助?

#include <iostream>
#include <queue>
#include <ctime>
#define queueSize 10 
#define arraySize 50
#define numberOfDigits 3

int getTheDigit(int num, int count);

using namespace std;

int main(void) {

srand(time(NULL)); // random seed
int randomNumbers[arraySize], indexCount = 0; 
queue <int> sorter[queueSize];

// generating 3 digit random numbers
while(indexCount < arraySize) { randomNumbers[indexCount++] = rand() % 890 + 100; }

// printing all the unsorted random numbers
for(int count = 0; count < arraySize; count++){
    if(count %10 == 0) puts("");
    cout << randomNumbers[count] << " "; 
}
puts("\n");

int putbackCount = 0, whileCount = 0;

for(int outerCount = 0; outerCount < numberOfDigits; outerCount++){
    for(int count = 0; count < arraySize; count++){
        int theDigit = getTheDigit(randomNumbers[count], outerCount+1);
        printf("%d. number: %d Digit: %d\n", count+1, randomNumbers[count], theDigit); // debugging statement
        sorter[theDigit].push(randomNumbers[count]); 
    }   
    puts("");

        //dumping the stack back to the array for another pass
        while(whileCount < queueSize){
            if(whileCount % 10 == 0) puts("");
            while(!sorter[whileCount].empty()){
                randomNumbers[putbackCount++] = sorter[whileCount].front(); sorter[whileCount].pop();   
            }   
            whileCount++;
        }       
}
printf("\nSORTED ARRAY\n");

 for(int count = 0; count < arraySize; count++){
    if(count % 10 == 0) puts("");
    cout << randomNumbers[count] << " ";
 }
puts("\n");

return 0;
}

int getTheDigit(int num, int count){ 

switch(count){
    case 1: return num%10; break;
    case 2: return num/10%10; break;
    case 3: return num/100; break;
}
return (int)NULL;
}   

0 个答案:

没有答案