【题目来源】
https://oj.czos.cn/p/1010
【题目描述】
对数组的元素按从小到大进行排序。
【输入格式】
第一行有一个整数 n(5≤n≤10);
第二行有 n 个整数,每个整数的值在 0, 10\^9的范围内。
【输出格式】
输出排序后的数组。
【输入样例】
8
1 2 3 6 8 7 4 5
【输出样例】
1 2 3 4 5 6 7 8
【数据范围】
5≤n≤10
【算法分析】
● 桶排序:https://oi-wiki.org/basic/bucket-sort/
桶数优先选 10、20、100,或等于元素个数 n。
值域超大(1e5、1e9)时,固定桶数为 50~100,即桶数不随着值域变化。
gap=(最大值一最小值)+桶数量。
● 严谨来说,如下"桶排序"的代码是有 bug 的。即一维数组一旦开到本题所需的 1e9 的水准,必然内存溢出,报错。但测试时,取 N=1e3+5,也通过了。
cpp
#include <bits/stdc++.h>
using namespace std;
const int N=1e3+5;
int a[N];
int n,x;
int main() {
cin>>n;
for(int i=1; i<=n; i++) {
cin>>x;
a[x]++;
}
for(int i=1; i<N; i++) {
while(a[i]) {
cout<<i<<" ";
a[i]--;
}
}
return 0;
}
/*
in:
5
6 9 2 7 1
out:
1 2 6 7 9
*/
故考虑利用动态数组 vector 进行优化。
【算法代码:桶排序】
cpp
#include <bits/stdc++.h>
using namespace std;
const int bkt_num=10;
vector<int> bkt[bkt_num];
int n,x;
int main() {
cin>>n;
int gap=100;
for(int i=0; i<n; i++) {
cin>>x;
int id=x/gap;
bkt[id].push_back(x);
}
for(int i=0; i<bkt_num; i++) {
sort(bkt[i].begin(),bkt[i].end());
for(int x:bkt[i]) {
cout<<x<<" ";
}
}
return 0;
}
/*
in:
5
6 9 2 7 1
out:
1 2 6 7 9
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/161347829
https://blog.csdn.net/hnjzsyjyj/article/details/161332702
https://blog.csdn.net/hnjzsyjyj/article/details/161346075
https://blog.csdn.net/hnjzsyjyj/article/details/161588834
https://blog.csdn.net/hnjzsyjyj/article/details/119820490
https://blog.csdn.net/hnjzsyjyj/article/details/119819927