东方博宜OJ 1010:数组元素的排序 ← 桶排序

【题目来源】
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

相关推荐
m0_639906946 小时前
Redis入门|五种数据结构、使用场景、持久化RDB&AOF
数据结构·数据库·redis
2601_9707038310 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
丘山望岳15 小时前
单调栈和单调队列
数据结构
UIU11418 小时前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
旖旎夜光19 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
黎相思21 小时前
BTree
数据结构·b树·b+树
UIU1141 天前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
niyongsheng1 天前
3D 装箱算法工程化:数据结构、放置启发式与支撑规则
数据结构·算法·rust
叉烧滑蛋2 天前
B站台湾大学郭彦甫|MATLAB 学习笔记|04 变量与档案存取
数据结构
j7~2 天前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归