Reputation: 11
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
Reputation: 81986
b
.bi == 9
.bi == 9
, b[bi]
accesses beyond the end of the array.Upvotes: 5