java源码之PriorityQuene

Java中PriorityQueue通过二叉小顶堆实现,可以用一棵完全二叉树表示。

刚刚做到剑指offer最小的K个数,最开始用了快速排序的方式做的,但是时间复杂度有点高,看了评论说是用堆排序要好些,看到了优先队列是用堆实现的,所以这里简单介绍下优先队列

对于堆排序的数据结构 实现形式不懂的可以先看看 数据结构的书

 

看下优先队列一些基本的数据结构,一个默认的初始化容量 object的数组作为堆的底层实现 容量大小size


    private static final int DEFAULT_INITIAL_CAPACITY = 11;

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

    private int size = 0;

方法介绍

grow() 增加优先队列容量 

容量不够时,如果老容量比64小则双倍增加,否则增加一半;如果增加后的容量特别大,则采用其他策略

    private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // Double size if small; else grow by 50%
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));
        // overflow-conscious code
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        queue = Arrays.copyOf(queue, newCapacity);
    }

add()和offer() 向堆中添加堆节点

add()调用offer方法;offer方法代码中的边界判断比较简单,这边讲一讲向上调整方法siftUp(i,e)  见代码注释

   public boolean add(E e) {
        return offer(e);
    }


    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }
    private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x); //如果构造优先队列的时候传入了比较器,则使用这个方法
        else
            siftUpComparable(k, x);  //否则使用此方法
    }

/**
这边默认小顶堆,k为最后一位的下标,插入的值大于父节点值的时候终止;否则和父节点交换,直到堆顶
*/

    @SuppressWarnings("unchecked")
    private void siftUpComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;  //父节点下标为(k-1)/2
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0) 
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }

    @SuppressWarnings("unchecked")
    private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

 

remove看着有点复杂懒得说了。。聊聊常用的poll()方法

poll()方法移出堆顶节点

//移出堆顶,堆顶为空之后肯定是要调整堆的  siftDown()用来调整堆
    public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        E result = (E) queue[0];
        E x = (E) queue[s];  //将堆最后的值记录下来,用来将来放到堆顶,调整堆
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }

/**
和向上调整类似,移出堆顶后需要向下调整,循换与左右孩子最小的比较(当父节点不超过堆结点一般的时候),父节点小于等于孩子节点时终止。
*/
    private void siftDown(int k, E x) {
        if (comparator != null)
            siftDownUsingComparator(k, x);
        else
            siftDownComparable(k, x);
    }

    @SuppressWarnings("unchecked")
    private void siftDownComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>)x;
        int half = size >>> 1;        // loop while a non-leaf
        while (k < half) {
            int child = (k << 1) + 1; // assume left child is least
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
                c = queue[child = right];
            if (key.compareTo((E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = key;
    }

    @SuppressWarnings("unchecked")
    private void siftDownUsingComparator(int k, E x) {
        int half = size >>> 1;
        while (k < half) {
            int child = (k << 1) + 1;
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                comparator.compare((E) c, (E) queue[right]) > 0)
                c = queue[child = right];
            if (comparator.compare(x, (E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = x;
    }

 

常用的方法先介绍到这里

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值