这是一个桶排序程序。显示'9'作为输出后,该程序崩溃。我无法识别错误。我想错误应该是创建存储桶索引但我无法弄明白。
#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;
}
答案 0 :(得分:5)
b
的6个存储桶的数组。bi == 9
。bi == 9
,b[bi]
访问超出数组末尾。