1

I am trying to learn the bucket sort algorithum in C++ and i found the following code:

// C++ program to sort an array using bucket sort 
#include <iostream> 
#include <algorithm> 
#include <vector> 
using namespace std;

// Function to sort arr[] of size n using bucket sort 
void bucketSort(float arr[], int n)
{
    // 1) Create n empty buckets 
    vector<float> b[n];

    // 2) Put array elements in different buckets 
    for (int i = 0; i < n; i++)
    {
        int bi = n * arr[i]; // Index in bucket 
        b[bi].push_back(arr[i]);
    }

    // 3) Sort individual buckets 
    for (int i = 0; i < n; i++) sort(b[i].begin(), b[i].end());

    // 4) Concatenate all buckets into arr[] 
    int index = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < b[i].size(); j++)
            arr[index++] = b[i][j];
}

int main()
{
    float arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 };
    int n = sizeof(arr) / sizeof(arr[0]);
    bucketSort(arr, n);

    cout << "Sorted array is \n";
    for (int i = 0; i < n; i++) cout << arr[i] << " ";
    return 0;
}

But it gives me several errors:

alt text

It seems that it wants the arrays to be dynamical in order n not to be constant. I tried to do that with:

float* b = new float[n];

or something like that; but nothing came out. Why is doing that, and how can I fix it?

JeJo
  • 30,635
  • 6
  • 49
  • 88
andy489
  • 125
  • 2
  • 9
  • `int bi = n * arr[i]` won't work. The bucket index should be less than `n`, not more. – rustyx Aug 12 '19 at 11:38
  • 1
    All questions on stackoverflow must include all pertinent information ***in plain text*** instead of unreadable images. Please [edit] the question and replace that big unreadable image with the plain error message. – Sam Varshavchik Aug 12 '19 at 11:44

1 Answers1

5

Variable-length arrays are not part of standard C++. That means, this

vector<float> b[n];

is illegal and has to be replaced. In modern c++, you have std::vector which stores its elements dynamically and manage the memory allocations as per need. You have already used but not completely. It looks like you need to replace it with

std::vector<std::vector<float>> b(n);
JeJo
  • 30,635
  • 6
  • 49
  • 88