我一直在研究一种基数桶排序算法,我先从两位数开始,然后逐步增加到更多位数。
我硬编码循环运行2次(因为我硬编码的数字中有2位数字),并且在第二个循环中有一个错误我无法确定。
介于清除数据向量和将值从存储桶推送到数据向量之间的某个地方,有些地方出错了……有什么想法吗?
错误只发生在一些数字输入…和其他人一样,我评论过它是有效的。

#include <math.h>
#include <iostream>
#include <vector>

using namespace std;

// test radix_sort
int main() {
    cout << "==================================\n";
    cout << "Radix bucket sort DEBUG ME\n";
    cout << "==================================\n\n";

    int m = 10;
    int n = 1;

    int arr[] = { 17, 45, 75, 90, 02, 24, 26, 06 }; //create data array
    //int arr[] = { 170, 405, 750, 302, 002, 240, 206, 006 }; //create data array
    vector<int> data (arr, arr + sizeof(arr) / sizeof(arr[0]) ); //create data vector
    int elements = data.size();

    //print data vector
    cout << "Original: ";
    for (int i = 0 ; i < elements ; i++){
    cout << data[i] << " ";
    }
    cout << endl;

    vector< vector<int> > vec(10, vector<int>(0));; //create buckets vector

    for (int t = 0 ; t < 2 ; t++){ //hard coded to run 2 times since max 2 digits

        for (int i = 0 ; i < elements ; i++) //radix sort into buckets
        {
            vec[(data[i]%m)/n].push_back(data[i]);
        }
        data.clear(); //clear from data vector

        for (int i = 0 ; i < elements ; i++) //push buckets in order onto data
        {
            for (int j = 0 ; j < vec[i].size() ; j++)
            {
                data.push_back(vec[i][j]);
            }
        }

        cout << "#" << t+1 << ": ";
        for (int i = 0 ; i < elements ; i++){ //print data vector
            cout << data[i] << " ";
        }
        cout << endl;


        //multiply modulus by 10
        m = m*10;
        n= n*10;

        for(int i = 0 ; i < 10 ; i++){ //clear all the shit from buckets
            vec[i].clear();
        }
    }
    return 0;
}

最佳答案

将值从vec移回data,您需要遍历所有10个bucket,而只需遍历其中的8个bucket:

   for (int i = 0 ; i < elements ; i++) // elements == 8
   {
        for (int j = 0 ; j < vec[i].size() ; j++)
        {
            data.push_back(vec[i][j]);
        }
    }

这应该是:
   for (int i = 0 ; i < vec.size(); i++) // vec.size() == 10
   {
        for (int j = 0 ; j < vec[i].size() ; j++)
        {
            data.push_back(vec[i][j]);
        }
    }

关于c++ - 基数桶搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29135668/

10-11 07:09