如何解决使用向量的细分问题在C ++中实现存储桶排序
我正在研究使用向量的Bucket Sort算法的实现。在第一个循环中,出现了分段错误,我看不出为什么。在发布此问题之前,我一直在寻找类似的问题(例如this或this one),但我在那里找不到答案。
该实现取自here。由于它在这里发布,我以为它应该可以工作,可能是与编译器有关的问题(我正在使用 g ++ )?
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());
}
}
}
我正在使用此驱动程序代码对其进行测试:
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;
}
谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。