成绩排序

成绩排序

http://www.nowcoder.com/questionTerminal/8e400fd9905747e4acc2aeed7240978b

使用 Comparator

import java.util.*;

class Student{
    private int grade;
    private String name;
    public static final Comparator<Student> INCREASE = new increase();
    public static final Comparator<Student> DECREASE = new decrease();
    public Student(String name, int grade) {this.name = name;
        this.grade = grade;
    }
    public String toString() {
        return name + " " + grade;
    }
    private static class increase implements Comparator<Student> {
        public int compare(Student v, Student w) {
            return w.grade - v.grade;
        }
    } 
    private static class decrease implements Comparator<Student> {
        public int compare(Student v, Student w) {
            return v.grade - w.grade;
        }
    }
}
public class Main { 

    public Main() {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = Integer.valueOf(in.next());
            int flag = Integer.valueOf(in.next());
            Student[] students = new Student[n];
            for (int i = 0; i < n; i++) {
                students[i] = new Student(in.next(), Integer.valueOf(in.next()));
            }
            if (flag == 1) {
                Arrays.sort(students, Student.DECREASE);
            }
            else {
                Arrays.sort(students, Student.INCREASE);
            }
            for (Student student : students) {
                System.out.println(student);
            }
        }
    }

    public static void main(String[] args) 
    {
        Main solution = new Main();
    } }
全部评论
题目的意思是1升序increase,0降序decrease, 你命名含义弄反了吧?但是结果是对的
3 回复 分享
发布于 2022-03-29 15:27
升序和降序的反了吧,自然排序应该是升序
3 回复 分享
发布于 2022-03-30 21:13
请问这个怎么保证相同分数的次序保持不变呢?
2 回复 分享
发布于 2021-11-13 15:36
妙啊
点赞 回复 分享
发布于 2021-03-20 15:25
巴适得很呀
点赞 回复 分享
发布于 2021-05-06 16:56
Arrays.sort是不能保证相同元素的次序的吧?
点赞 回复 分享
发布于 2021-12-02 15:57

相关推荐

24 7 评论
分享
牛客网
牛客企业服务