成绩排序_牛客网

成绩排序(查找和排序)

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。

示例:
jack 70
peter 96
Tom 70
smith 67

从高到低 成绩
peter 96
jack 70
Tom 70
smith 67

从低到高
smith 67
jack 70
Tom 70
peter 96

代码实现:

import java.util.*;
class student{
    String name;
    int score;
    public student(String name,int score){
        this.name=name;
        this.score=score;
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        while(input.hasNext()) {
            int n = input.nextInt();//要排序的人的个数
            int order=input.nextInt();//排序方式
            List<student> list=new ArrayList<>();
            for (int i = 0; i < n; i++) {
                String name = input.next();
                int score=input.nextInt();
                list.add(new student(name,score));
            }
            //降序
            if(order==0){
                Collections.sort(list, new Comparator<student>() {
                    @Override
                    public int compare(student o1, student o2) {
                        return o2.score-o1.score;
                    }
                });
            }
            //升序
            if(order==1){
                Collections.sort(list, new Comparator<student>() {
                    @Override
                    public int compare(student o1, student o2) {
                        return o1.score-o2.score;
                    }
                });
            }
            for(int i=0;i<list.size();i++){
                System.out.println(list.get(i).name+" "+list.get(i).score);
            }
        }
    }
}
发布了71 篇原创文章 · 获赞 2 · 访问量 7480

猜你喜欢

转载自blog.csdn.net/weixin_42512675/article/details/103308549