牛客网考研复试题-成绩排序

题目地址:https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1?tpId=40&tqId=21333&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

题解:结构体cmp排序,但是要注意是稳定排序,加一个index的标记

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 struct student{
 7     char name[20];
 8     int grade;
 9     int index;
10 };
11 struct student stu[55];
12 int  cmp1(struct student a,struct student b){//升序
13     if(a.grade==b.grade){
14         return a.index<b.index;
15     }else{
16         return a.grade<b.grade;
17     }
18 
19 }
20 int  cmp2(struct student a,struct student b){//降序
21     if(a.grade==b.grade){
22             return a.index<b.index;
23         }else{
24             return a.grade>b.grade;
25     }
26 }
27 int main(){
28     int flag,num;
29     while(scanf("%d %d",&num,&flag)!=EOF){
30         for(int i=0;i<num;i++){
31             scanf("%s %d",stu[i].name,&stu[i].grade);
32             stu[i].index=i;
33         }
34         if(flag==1){
35             sort(stu,stu+num,cmp1);
36             for(int  i=0;i<num;i++){
37                 printf("%s %d
",stu[i].name,stu[i].grade);
38             }
39         }else{
40             sort(stu,stu+num,cmp2);
41             for(int  i=0;i<num;i++){
42                 printf("%s %d
",stu[i].name,stu[i].grade);
43             }
44         }
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/cutelife/p/12047995.html