题目描述
查找和排序
题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。
例示:
jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
Tom 70
jack 70
peter 96
笔者最近在准备18年研究生复试,网络空间安全专业有机考,在牛客网上找了些往年机考真题,发现这道题通过率较低,而笔者恰好对本题所涉及到的知识较熟悉。(c语言里的指针好久没看了,有点生疏)写点东西记录下
#include<stdio.h>
typedef struct
{
char name[1000];
int score;
}student;
int main()
{
student stu[1000];
int num;
int way; //用来显示方式:0降序。1升序
int i,j;
student temp;
while (scanf("%d %d", &num, &way) != EOF)
{
for(i=0; i < num; i++)
scanf("%s %d", &stu[i].name, &stu[i].score);
if(way == 0) //冒泡排序 从大到小
{
for(i = 0; i < num; i++)
for(j = 0; j <num-1-i; j++)
if(stu[j].score < stu[j+1].score)
{
temp = stu[j+1];
stu[j+1] = stu[j];
stu[j] = temp;
}
}
else{ //冒泡排序 从小到大
for(i = 0; i < num - 1; i ++)
for(j = 0; j <num-1-i; j++)
if(stu[j].score > stu[j+1].score)
{
temp = stu[j];
stu[j] = stu[j+1];
stu[j+1] = temp;
}
}
for(i = 0; i < num; i++) //输出
printf("%s %d\n", stu[i].name, stu[i].score);
}
return 0;
总的来说此题不难理解,主要用到结构体数组和冒泡排序。在考试题目里面,代码量相对多一点。