东方博宜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

相关推荐
AI情绪识别开源13 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
伟大的车尔尼19 小时前
贪心的概念
数据结构·算法·贪心
AI情绪识别开源19 小时前
检信AI高一分班分科智选评估系统 v2.0测试报告
开发语言·数据结构·人工智能·科技
CoderYanger20 小时前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
雪碧聊技术21 小时前
KMP算法详解
数据结构
positive_zpc1 天前
进阶数据结构图——关键路径(四)
数据结构·图论·关键路径
孙克旭_1 天前
单链表进阶实操:5 道常考面试题详细解析【Java 实现】
java·开发语言·数据结构·单链表
Chester_19991 天前
CSP202206C.角色授权
开发语言·数据结构·c++·蓝桥杯
旖旎夜光1 天前
LeetCode 238:除自身以外数组的乘积(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
一条大祥脚1 天前
26杭电暑期第八场(后半)快读|快写|tarjan|路径DP|mex转化|扫描线|前缀和|二分图
数据结构·算法·tarjan·杭电多校·强联通分量·动态规划dp