题解 | #成绩排序#
成绩排序
http://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
//这题如果用Collections的sort方法进行用比较器排序,是不稳定的,需要用Arrays的比较器排序
import java.io.;
import java.util.;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int flag = sc.nextInt();
Student[] stu=new Student[n];
for (int i = 0; i < n; i++) {
stu[i]=new Student(sc.next(),sc.nextInt());
}
sort(stu,flag);
for (Student student:stu){
System.out.println(student.name+" "+student.score);
}
}
}
//使用比较器排序 public static void sort(Student[] stu,int flag){ if (flag==1){ Arrays.sort(stu, new Comparator() { @Override public int compare(Student o1, Student o2) { return o1.score-o2.score; } }); }else if (flag==0){ Arrays.sort(stu, new Comparator() { @Override public int compare(Student o1, Student o2) { return o2.score-o1.score; } }); } }
}
//创建一个学生类
class Student{
String name;
int score;
Student(String name,int score){
this.name=name;
this.score=score;
}
}