c++封装的sort函数基于快速排序,不稳定; 写个冒泡排序,稳定
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
struct Student{
string name;
int score;
};
void downsort(Student *student,int n){
for(int i=0;i<n-1;i++){
for(int j=n-2;j>=i;j--)
if(student[j].score<student[j+1].score)
swap(student[j],student[j+1]);
}
}
void upsort(Student *student,int n){
for(int i=0;i<n-1;i++){
for(int j=n-2;j>=i;j--)
if(student[j].score>student[j+1].score)
swap(student[j],student[j+1]);
}
}
int main(){
int n;
int method;
while(cin>>n>>method){
Student student[n];
for(int i=0;i<n;i++){
cin>>student[i].name;
cin>>student[i].score;
}
if(method==0)
downsort(student,n);
if(method==1)
upsort(student,n);
for(int i=0;i<n;i++)
cout<<student[i].name<<' '<<student[i].score<<endl;
}
}