题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1
冒泡排序
#include <stdio.h>
#include <stdlib.h>
struct exam_info {
char name[10];
int score;
};
void ascend(struct exam_info* temp, int num) {
for (int i = 0; i < num-1; i++) {
for (int j = 0; j < num-i-1; j++) {
if (temp[j].score > temp[j+1].score) {
struct exam_info t = temp[j];
temp[j] = temp[j+1];
temp[j+1] = t;
}
}
}
}
void descend(struct exam_info* temp, int num) {
for (int i = 0; i < num-1; i++) {
for (int j = 0; j < num-i-1; j++) {
if (temp[j].score < temp[j+1].score) {
struct exam_info t = temp[j];
temp[j] = temp[j+1];
temp[j+1] = t;
}
}
}
}
void input_score(struct exam_info* temp, int num){
for(int i = 0;i<num;i++){
printf("%s %d\n",temp[i].name,temp[i].score);
}
}
int main() {
int num;
int method;
while(scanf("%d",&num)!=EOF){
scanf("%d", &method);
struct exam_info stu_info[num];
for (int i = 0; i < num; i++) {
scanf("%s %d", stu_info[i].name, &stu_info[i].score);
}
if (method) {
ascend(stu_info, num);
input_score(stu_info,num);
} else {
descend(stu_info, num);
input_score(stu_info,num);
}
}
return 0;
}
