Java PriorityQueue详解

优先队列PriorityQueue是一个堆,默认是小根堆(是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于其左子节点和右子节点的值), 即堆顶是最小值,叶子结点大于父节点。
若向PriorityQueue传递一个比较器,可以实现自定义的比较顺序,实现大根堆。

首先看成员变量,核心成员变量是:数组queue, 数组大小size,比较器comparator

    transient Object[] queue; // non-private to simplify nested class access

    /**
     * The number of elements in the priority queue.
     */
    private int size = 0;

    /**
     * The comparator, or null if priority queue uses elements'
     * natural ordering.
     */
    private final Comparator<? super E> comparator;

核心函数:siftUpComparable ,作用是在每新加一个对象,将该对象放在堆中应该放的位置。

private void siftUpComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;      // 计算父节点的index
            Object e = queue[parent];       // 父节点
            if (key.compareTo((E) e) >= 0)     // 大于父节点,说明堆不用调整
                break;
            queue[k] = e;     // 小于父节点,父节点已到当前结点,继续调整,直到把key放到应该放的位置
            k = parent;
        }
        queue[k] = key;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值