数据结构之二叉堆

二叉堆
是一棵完全二叉树,插入节点时按照顺序尽量插在左边,采用数组实现,二叉堆规定子节点的值一定小于或者大于父节点。

PrioityQueue中二叉堆原理应用
JDK1.5中怎么使用的
PrioityQueue特殊的二叉堆 并且每一层的元素从左往右顺序插入
节点之间有一定的关系
设父节点小标为p 左孩子 下标l 右孩子下标r
p=(c-1)/2;
l=p*2+1;
r=p*2+2;
通过公式发现它适合用数组结构存储
所以PrioityQueue的peek()/element()操作时O(1)
而add()/offer()/poll()/remove()操作时O(log(n)).

分别来讲一下这几个方法
add()/offer都是向优先队列中插入元素
先看add()方法

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

add()直接调用offer()方法返回
再看offer()方法

public boolean offer(E e) {
        //PrioityQueue元素不允许为null
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        //如果数组需要扩容,arraycopy操作
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;//队列为空时第一个元素插在数组开头
        else
            siftUp(i, e);//队列部位空时堆结构调整元素位置
        return true;
    }

相关的两个函数也看一下

 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);
    }
private void siftUp(int k, E x) {
        //使用不同的比较器进行比较
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

siftUpComparable点进去

 private void siftUpComparable(int k, E x) {
        //k为CurrentNodeIndex,x为要插入的元素
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
            //等价于前面的计算方法p=(c-1)/2
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            //将x逐层与parent元素交换,直到x>=queue[parent]
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }

最后附上一张图大家理解下
这里写图片描述
再者分析peek()/element()操作 都是取出堆顶元素但不删除。
区别是element()实现是peek()但取出元素null抛出异常而peek()不会。
element的实现在AbstractQueue中已经实现

public E element() {
        E x = peek();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

还是看代码

public E peek() {
        return (size == 0) ? null : (E) queue[0];
    }

附上一张演示流程图
这里写图片描述
剩下poll()/remove()操作
remove()在基类中实现了,如果返回为null,抛出异常

 public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

poll()取出堆顶并删除 ,失败返回null.

 public E poll() {
         //堆为空删除失败返回null
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        //获取堆顶元素
        E result = (E) queue[0];
        //取出数组最后一个元素,相当于完全二叉树的最后一个
        E x = (E) queue[s];
        //最后一个元素置null
        queue[s] = null;
        //如果堆不止只有一个元素那么调整
        if (s != 0)
            siftDown(0, x);
        return result;
    }

重点还是在siftDown(0,x)上

  private void siftDown(int k, E x) {
        if (comparator != null)
            siftDownUsingComparator(k, x);
        else
            siftDownComparable(k, x);
    }
//k直接从0开始,x为最后二叉堆一个
 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;
    }
    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;
    }

最后附上一张流程演示图
删除堆顶 把最后的元素放入堆顶 向调整
这里写图片描述

最后还有一个remove()返回boolean类型 调用removeAt(i)

public boolean remove(Object o) {
        int i = indexOf(o);
        if (i == -1)
            return false;
        else {
            removeAt(i);
            return true;
        }
    }
//i是要删除的索引下标
private E removeAt(int i) {
        // assert i >= 0 && i < size;
        modCount++;
        int s = --size;
        if (s == i) // removed last element  删除的是最后一个元素
            queue[i] = null;
        else {
        //获取最后一个元素并置空
            E moved = (E) queue[s];
            queue[s] = null;
            //另queue[i]为最后一个元素并向下调整
            siftDown(i, moved);
            //当向下调整没有变化则需要上浮,说明最后一个元素换到i位置后是最小的元素
            if (queue[i] == moved) {
                siftUp(i, moved);
                if (queue[i] != moved)
                    return moved;
            }
        }
        return null;
    }

在附一张流程演示图
这里写图片描述

后续再仔细更新其他部分

最后心得是
在明确父子关系下尽量选择画图来解释siftDown和siftUp机制
Prioity是最小二叉堆并且元素不允许为null

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值