java借助PriorityQueue实现小根堆和大根堆

首先,明确概念:

堆是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于(或不小于)其左孩子和右孩子节点的值。

根结点(亦称为堆顶)的关键字是堆里所有结点关键字中最小者的堆称为小根堆。 

根结点(亦称为堆顶)的关键字是堆里所有结点关键字中最大者,称为大根堆。


借助类PriorityQueue 可以实现小根堆和大根堆。

对于PriorityQueue ,观察帮助文档,可以发现,这是jdk1.5以后引入的,

对它的说明如下:An unbounded priority  queue based on a priority heap,The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

                               The head of this queue is the least element with respect to the specified ordering.

由此可知,它容量没有界限,且默认排序是自然排序,队头元素是最小元素,故我们可以拿来作为小根堆使用。

(要注意:默认的PriorityQueue并非保证了整个队列都是有序的,只是保证了队头是最小的)

对于大根堆,就要借助于comparator比较器,来实现大根堆。(使用默认的初始容量:11)

[java]  view plain  copy
  1. PriorityQueue <Integer> maxHeap = new PriorityQueue<Integer>(11new Comparator<Integer>() {  
  2.   
  3.     @Override  
  4.     public int compare(Integer o1, Integer o2) {  
  5.         // TODO Auto-generated method stub  
  6.         return o2.compareTo(o1);  
  7.     }  
  8.       
  9. });  

这样就实现了,大根堆的功能。

猜你喜欢

转载自blog.csdn.net/weixin_40137479/article/details/80336055