小根堆是个好排序

小根堆PriorityQueue 是优先级队列,这是什么呢,就是默认优先依次取出最小值得那个对象,什么是最小值对象,就是你以为它小就是小,跟对象具体的大小无关,完全看比较器怎么判断的大小。时间复杂度O(n)

还是学生类比较,上代码:

//我的优先级队列
    
    public static void main(String[] args) {
        Student s1 = new Student("王二",5,29);
        Student s2 = new Student("王五",5,30);
        Student s3 = new Student("王七",7,29);
        Student s4 = new Student("王一",1,51);
        Student s5 = new Student("王四",4,51);
        Student s6 = new Student("王三",3,29);
        PriorityQueue<Student> queue = new PriorityQueue<>(new StudentCompare(true));
        queue.add(s1);
        queue.add(s2);
        queue.add(s3);
        queue.add(s4);
        queue.add(s5);
        queue.add(s6);
        while(!queue.isEmpty()) {
            //弹出
            Student poll = queue.poll();
            System.out.println(poll.name+"-"+poll.age+"-"+poll.id);
        }
        
        
    }
    //自定义比较方式类,通过参数true和false判断正序还是倒序,最终目的就是为了改变compare方法的返回值是-1还是1
    public static class StudentCompare implements Comparator<Student>{
        public int i=1;
        public StudentCompare(boolean flag) {
            if(flag) {
                this.i=-1;
            }
            
        }
        //说明:如果返回-1,o1在前,如果返回1,o2在前,如果返回0,o1在前
        @Override
        public int compare(Student o1, Student o2) {
            if(o1.id>o2.id) {
                return -1*i;
            }else if(o1.id<o2.id) {
                return 1*i;
            }else {
                if(o1.age>o2.age) {
                    return 1*i;
                }else if(o1.age<o2.age) {
                    return -1*i;
                }
            }
            return 0;
        }
        
    }
    
    //定义学生类
    public static class Student{
        public Student(String name,int age,int id) {
            this.name=name;
            this.age = age;
            this.id = id;
        }
        public String name;
        public int age;
        public int id;
        
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值