桶排应用——数据量大而范围小的排序

桶排应用——数据量大而范围小的排序

题目描述 Little Gyro has just found an integer sequence a1,a2,…,an in his right pocket. As Little Gyro is bored, he decides to sort the
sequence. Now given an integer sequence, and its size is no more than
106, please sort it within the ascending order.

输入描述: There are multiple test cases. The first line of the input contains an integer T, indicating the number of test cases. For each
test case: The first line contains an integer n (1 ≤ n ≤ 106),
indicating the length of the sequence. The second line contains n
integers a1,a2.,ana 1,a 2,…,a n(1 ≤ ai≤ 104 ), indicating the given
sequence. It’s guaranteed that the sum of n of all test cases will not
exceed 10^7 . 输出描述: For each test case output the sequence after
sorting. Note: Please, DO NOT output extra spaces at the end of each
line, or your answer may be considered incorrect!

输出描述: For each test case output the sequence after sorting. Note:
Please, DO NOT output extra spaces at the end of each line, or your
answer may be considered incorrect!


示例1
输入

2
5
1 4 8 3 7
6
10000 9999 9998 9997 9996 9995

输出

1 3 4 7 8
9995 9996 9997 9998 9999 10000

备注:

在这里插入图片描述

思路如下:

这题 就是对一组数据排序,但是数据的量非常大,但是数据的取值范围却不是很大,如果我们 直接用 sort()方法排序会直接时间超限,但是如果我们用桶排去解决这个问题,那么尽管数据量非常大,但是 桶排的时间增长是呈线性的,而不想sort()函数那那样随着数据增加到很大的时候,耗时就大幅增长

题解如下:
#include<iostream>
#include<string.h>
#include<algorithm>

using namespace std;
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
//        memset(buct,0,sizeof(buct));		//通过用memset去初始化buck的耗费的时间 比在定义数组的时候初始 耗时更长!!!
        int buct[10005] = {0};
        int n;
        scanf("%d",&n);
        int temp;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&temp);
            buct[temp]++;
        }
        int flag = 0;
        for(int j=0;j<10005;j++)
            for(int k=0;k<buct[j];k++)
                if(flag == 0)
                {
                    printf("%d",j);
                    flag = 1;
                }
                else
                    printf(" %d",j);
            printf("\n");
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值