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

相关推荐
刘马想放假3 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
北域码匠4 天前
冒泡排序太慢?鸡尾酒排序双向优化,原生 C# 零第三方库完整代码
数据结构·排序算法·泛型·c# 算法·鸡尾酒排序·原生 c# 开发·冒泡排序优化·嵌入式算法
To_OC5 天前
手写快排次次翻车?别死背快排模板了,这才是面试官想听的底层逻辑
javascript·算法·排序算法
Darling噜啦啦5 天前
快速排序与递归思维:从分治策略到数组扁平化——面试必考算法全解析
面试·排序算法
用户484526255826 天前
搜索旋转排序数组:必有一侧是有序的
排序算法
用户484526255826 天前
翻转二叉树:前序和后序的写法完全一样
排序算法
用户484526255826 天前
对称二叉树:左子树的左和右子树的右对比
排序算法
Darling噜啦啦11 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
小小工匠12 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化