考察的内容的话其实是排序稳定和如何排序,这个的话sort底层数据量小的时候是冒泡,数据量大的时候是快排,其实是不稳定的,所以这里需要自己写排序,想写归并来着,归并的话代码更多,先是试了下冒泡,其实是没有超时的,所以就用了冒泡排序。这里的话swap是可以对结构体进行交换的,这个之前我没有用过
#include
#include
#include
using namespace std;
struct student{
string name;
int score;
}stu[1005];
int flag,n;
void popSort0(){
for(int i=n-1;i>0;i--){
for(int j=0;j<i;j++){
if(stu[j].score<stu[j+1].score){
swap(stu[j],stu[j+1]);
}
}
}
}
void popSort1(){
for(int i=n-1;i>0;i--){
for(int j=0;j<i;j++){
if(stu[j].score>stu[j+1].score){
swap(stu[j],stu[j+1]);
}
}
}
}
int main(){
while(cin>>n>>flag){
for(int i=0;i<n;i++){
cin>>stu[i].name>>stu[i].score;
}
if(flag==1){
popSort1();
}else{
popSort0();
}
for(int i=0;i<n;i++){
cout<<stu[i].name<<" "<<stu[i].score<<endl;
}
}
return 0;
}
京公网安备 11010502036488号