void bucketSort(int a[], int size) {
// 计算最大数值和最小数值
int mx = INT_MIN;
int mn = INT_MAX;
for (int i = 0; i < size; i++) {
mx = std::max(mx, a[i]);
mn = std::min(mn, a[i]);
}
std::cout << "mx: " << mx << std::endl;
std::cout << "mn: " << mn << std::endl;
std::cout << "size: " << size << std::endl;
// 计算桶的数量, 为什么这样规定桶的数量
int bucketNum = (mx - mn)/size + 1;
std::vector<int> Buckets[bucketNum];
// 将每个元素放入桶中
for (int i = 0; i < size; i++) {
int num = (a[i] - mn) / size;
Buckets[num].push_back(a[i]);
}
// 对每一个桶进行排序
for (int i = 0; i < bucketNum; i++) {
std::sort(Buckets[i].begin(), Buckets[i].end());
}
// 将桶中的元素赋值到原来的序列
int index = 0;
for (int i = 0; i < bucketNum; i++) {
for (int j = 0; j < Buckets[i].size(); j++) {
a[index++] = Buckets[i][j];
}
}
}
int main(int argc, char* argv[]) {
/* code */
int a[] = {1, 7, 8, 0, 10};
int size= sizeof(a) / sizeof(a[0]);
bucketSort(a, size);
for (int i= 0; i < size; i++) {
std::cout<<a[i]<<std::endl;
}
return 0;
}
桶排序C++
最新推荐文章于 2022-11-23 15:56:30 发布