题解 | #成绩排序#

成绩排序

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;
}
}

全部评论
说反了吧,Collections的sort 是稳定的;Arrays 的sort 用的是快排,是不稳定的。
2 回复 分享
发布于 2021-12-22 10:04

相关推荐

10-21 00:37
已编辑
门头沟学院 C++
小浪_Coding:你问别人,本来就是有求于人,别人肯定没有义务免费回答你丫, 有点流量每天私信可能都十几,几十条的,大家都有工作和自己的事情, 付费也是正常的, 就像你请别人搭把手, 总得给人家买瓶水喝吧
点赞 评论 收藏
分享
评论
2
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务