Segmentation problem using vectors (implementing Bucket Sort in C++)

95 Views Asked by At

I'm working on an implementation of the Bucket Sort algorithm that uses vectors. In the first loop a Segmentation Fault is raised and I can't see it why. Before posting this question I've been looking similar ones (like this or this one) but I haven't found the answer there.

The implementation is taken from here. Since it is publish here I had supposed that it should work, could be a problem related with the compiler (I'm using g++)?

The fragment of code is this one, just changed the name of some of the variables from the original example:

void bucketSort(float arr[], int n){

    vector<float> buckets[n];  

    // Here is where the bug must be!!
    for (int i = 0; i < n; i++){
        int bi = n * arr[i]; // Index in bucket
    buckets[bi].push_back(arr[i]);
    }

    for (int i = 0; i < n; i++){
        sort(buckets[i].begin(), buckets[i].end());
    }

    int index = 0;
    for (int i = 0; i < n; i++){
        while (!buckets[i].empty()){
            arr[index++] = *(buckets[i].begin());
            buckets[i].erase(buckets[i].begin());
        }
    }
}

I'm using this driver code to test it:

int main(){
    float arr[] = {8.0, 9.231, 1.31, 3.1, 42.2, 4.3, 99.999};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Length of the array: " << n << endl;

    cout << "Original array: " << endl;
    for (int i = 0; i < n; i++){
        cout << arr[i] << " ";
    }
    cout << endl;

    bucketSort(arr, n);

    cout << "Sorted array: " << endl;
    for (int i = 0; i < n; i++){
        cout << arr[i] << " ";
    }
    cout << endl;
}

Thanks!

0

There are 0 best solutions below