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

相关推荐
小欣加油1 小时前
Leetcode31 下一个排列
数据结构·c++·算法·leetcode·职场和发展
凤凰院凶涛QAQ1 小时前
《Java版数据结构 & 集合类剖析》链表与LinkedList:节点手拉手,增删不用愁
java·数据结构·链表
无限进步_2 小时前
【Linux】进程状态、僵尸与孤儿、进程调度
linux·运维·服务器·开发语言·数据结构·算法
郝学胜-神的一滴2 小时前
力扣 662 :二叉树最大宽度
java·数据结构·c++·python·算法·leetcode·职场和发展
小欣加油2 小时前
leetcode169 多数元素
数据结构·c++·算法·leetcode·职场和发展
代码中介商2 小时前
图论实战:最小生成树与拓扑排序精解
数据结构
SHARK_pssm2 小时前
【数据结构——双向链表】
数据结构·经验分享·笔记·链表
少司府2 小时前
C++进阶:AVL树
开发语言·数据结构·c++·二叉树·avl树
孬甭_3 小时前
从基础到优化:深入理解插入排序与希尔排序
数据结构·算法·排序算法