/*
桶排序最大值限定了需要开辟数组的最小目标。
优点:算法简单,速度较快其时间复杂度O(n), 为一次
缺点:浪费空间,空间利用率极低,如果遇到大批量数据处理,代价非常庞大。
情景模拟:假设存在5名同学 分别考了 5 , 4 , 5 ,2 , 9 分(满分10分)
利用桶排序方法对其进行排序。
*/
#include <stdio.h>
/*初始化模块*/
void input(int * a) //用于初始化数组,也就是输入用户得分
{
int i =0;
int core;
for(; i<11; i++)
a[i] = 0; //避免系统初始垃圾数值使他们都为0
for(i = 0; i< 5; i++)
{
scanf("%d",&core); //读取分数
a[core]++; //进行计量
}
}
/*升序排列*/
void increase(int *a)
{
int i = 0;
int j;
for(; i<11; i++) //读取分数,依次判断a[0] ~ a[10]
for(j = 1; j <= a[i] ; ++ j) //出现几次就打印几次
printf("%d ",i);
}
/*降序排列 只需用外层循环改变即可*/
void descending(int *a)
{
int i = 10;
int j;
for(; i>=0; i--) //读取分数,依次判断a[0] ~ a[10]
for(j = 1; j <= a[i] ; ++ j) //出现几次就打印几次
printf("%d ",i);
}
int main(void)
{
int a[11];
char ch ;
printf(" Please Input the Scores!\n");
input(a);
printf(" What order you want to Get ? \n Input 'I' if you want to Increase ,else system will output the descending sequence . \n" );
scanf("\n%c" , &ch);
if(ch =='I')
increase(a);
else
descending(a);
getchar();
getchar(); //用来暂停程序来查看 也可以使用 system("pause");
return 0;
}
#算法#C/C++#排序--桶排序
最新推荐文章于 2024-07-17 19:29:01 发布