JayJay
JayJay

Reputation: 11

This program crashes. I could not find the error

This is a bucket sort program. This program crashes after showing '9' as the output. I could not identify the error. I suppose the error should be in creating the bucket index but I could not figure it out.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

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

    // 2) Put array elements in different buckets
    for (int i=0; i<n; i++)
    {
       int bi = arr[i]; // Index in bucket
       while(bi > 9){
        bi = bi / 10;
       }
       cout << bi << endl;
       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];
}

/* Driver program to test above funtion */
int main()
{
    int arr[] = {97, 56, 65, 12, 65, 34};
    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;
}

Upvotes: 0

Views: 60

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81986

  1. You create an array of 6 buckets named b.
  2. On the first iteration of the for loop, you calculate bi == 9.
  3. With bi == 9, b[bi] accesses beyond the end of the array.
  4. undefined behavior.

Upvotes: 5

Related Questions