数据结构-排序(选做)

数据结构-排序(选做)
任务要求
在数据结构和算法中,排序是很重要的操作,要让一个类可以进行排序,有两种方法:
有类的源代码,针对某一成员变量排序,让类实现Comparable接口,调用Collection.sort(List)
没有类的源代码,或者多种排序,新建一个类,实现Comparator接口 调用Collection.sort(List, Compatator)
针对下面的Student类,使用Comparator编程完成以下功能:
在测试类StudentTest中新建学生列表,包括自己和学号前后各两名学生,共5名学生,给出运行结果(排序前,排序后)
对这5名同学分别用学号和总成绩进行增序排序,提交两个Comparator的代码
课下提交代码到码云

public class SortId {
    public static void main(String[] args) {
        Student[] student = new Student[5];
        student[0] = new Student("5305","zty",'n',20,67,78,77);

        student[1] = new Student("5306","wjs",'n',20,89,67,88);

        student[2] = new Student("5307","gsc",'n',20,99,77,89);

        student[3] = new Student("5309","lyh",'n',20,70,80,78);

        student[4] = new Student("5308","yy",'n',20,78,98,89);

        System.out.println("按照学号排序之后");
        for(int i=0;i<student.length;i++){
            int current = Integer.valueOf(student[i].getId());
            for(int j=i+1;j<student.length;j++){
                int temp = Integer.valueOf(student[j].getId());
                if(temp< current){
                    Student tem = new Student("","");
                    tem = student[j];
                    student[j]=student[i];
                    student[i]=tem;
                }

            }
        }
        for(Student q : student){
            System.out.println("Id:"+q.getId()+" Name:"+q.getName()+" Sex:"+q.getsex()+" Computer_score"+q.getComputer_score()+" English_score"+q.getEnglish_score()+" Maths_score"+q.getMaths_score());
        }
    }
}
public class SortScore {
    public static void main(String[] args) {
        Student[] student = new Student[5];
        student[0] = new Student("5305","zty",'n',20,67,78,77);

        student[1] = new Student("5306","wjs",'n',20,89,67,88);

        student[2] = new Student("5307","gsc",'n',20,99,77,89);

        student[3] = new Student("5309","lyh",'n',20,70,80,78);

        student[4] = new Student("5308","yy",'n',20,78,98,89);

        System.out.println("按照学号排序之后");
        for(int i=0;i<student.length;i++){
            double current = student[i].getTotalScore();
            for(int j=i+1;j<student.length;j++){
                double temp = student[j].getTotalScore();
                if(temp< current){
                    Student tem = new Student("","");
                    tem = student[j];
                    student[j]=student[i];
                    student[i]=tem;
                }

            }
        }
        for(Student q : student){
            System.out.println("Id:"+q.getId()+" Name:"+q.getName()+" Sex:"+q.getsex()+" Computer_score"+q.getComputer_score()+" English_score"+q.getEnglish_score()+" Maths_score"+q.getMaths_score());
        }
    }
}

posted on 2019-05-05 23:15  20175307GSC  阅读(99)  评论(0编辑  收藏  举报

导航