桶排应用——数据量大而范围小的排序
题目描述 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;
}