铲斗排序有大量随机数

时间:2014-11-28 02:43:54

标签: c++ bucket-sort

我知道Bucket sort在各地都有很多例子,所以我试图实现这个,所以它可以采取大量随机数而没有运气

void Bucket_sort(int arr[], int max){
     const int maxsize = max;
     int bucket_list = new int [maxsize+1];
     int length = sozeof(bucket_list) / sizeof(bucket[0]);
     for(int i = 0; i <max;i++){
         bucket_list[i] = 0; //fill with zeros
       }
       for (unsigned int i = 0; i <length; i++){
           bucket_list[arr[i]]++;
        }
        int position = 0;
        for (unsigned int i = 0 i < length; i++){
           for(int k = 0; k<bucket_list[i];k++){
                arr[position++] = i;
             }
          }
       }
      int main() {
         int max = 50000
         int arr[max];
         for (int i = 0; i < max; i++){
            arr[i] = rand() % 50000;
            }
            cout<<"Here are the numbers before Bucker Sort"<<endl;
            for (int j = 0; j < max; j++){
                 cout<<arr[j];
              }
            Bucket_sort(arr,max);
            for (int k = 0; k<max; k++){
               cout<<arr[k];
              }
           }

一些我怎么能让它工作,它只会输出相同的顺序(未排序) 我确实找到了与我相同的问题,但没有一个有帮助,这里有一个 https://stackoverflow.com/questions/20037176/c-bucket-sort-putting-integers-into-buckets

2 个答案:

答案 0 :(得分:2)

这一行:

bucket_list = 0; //fill with zeros

这是改变你的指针,而不是填充零。你应该使用

bucket_list[i] = 0; //fill with zeros

编辑:您的代码存在更多编译器问题。一旦你完成那些整理,length的计算仍然是错误的。您无法使用sizeof分割技巧,因为bucket_list不是数组。取代

int length = sozeof(bucket_list) / sizeof(bucket[0]);

int length = maxsize

或者根本不使用长度(你已经有maxsize)。

答案 1 :(得分:1)

#include<iostream>
#include<conio.h>
#include<stdlib.h>

using namespace std;

void Bucket_sort(int arr[], int max){

     int maxsize = max;
     int *bucket_list = new int[maxsize+1];
    // int length = sozeof(bucket_list) / sizeof(bucket[0]);
     int length = maxsize;
     for(int i = 0; i <max;i++){
         bucket_list[i] = 0; //fill with zeros
       }
       for (unsigned int i = 0; i <length; i++){
           bucket_list[arr[i]]++;
        }
        int position = 0;
        for (unsigned int i = 0 ; i < length ; i++){
           for(int k = 0; k<bucket_list[i];k++){
                arr[position++] = i;
             }
          }
       }
      int main() {
         int max = 50;
         int arr[max];
         for (int i = 0; i < max; i++){
            arr[i] = rand()%50;
            }
            cout<<"Here are the numbers before Bucker Sort"<<endl;
            for (int j = 0; j < max; j++){
                 cout<<arr[j];
              }
            Bucket_sort(arr,max);
            for (int k = 0; k<max; k++){
               cout<<arr[k];
              }
              getch();
              return 0;
           }