Java利用PriorityQueue类实现小根堆和大根堆(其中需要使用Comparator类)
堆:是一颗完全二叉树。通俗点说,一棵树最多只能最后一层不是满的,且不满的最后一层结点从左到右依次排列,那么这棵树就是完全二叉树。
小根堆每个结点都满足小于等于它的左右孩子结点,大根堆每个结点都满足大于等于它的左右孩子结点。
import java.util.Comparator;
import java.util.PriorityQueue;
public class HeapTest {
static PriorityQueue<Integer> min=new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer o1,Integer o2) {
return o1-o2;
}
});
static PriorityQueue<Integer> max=new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer o1,Integer o2) {
return o2-o1;
}
});
public static void main(String[] args) {
int[] a=new int[] {3,5,2,6,1,2,3,8,9,0};
for(int i=0;i<a.length;i++) {
min.offer(a[i]);
max.offer(a[i]);
}
//输出小根堆
while(min.size()>0) System.out.print(min.poll()+" ");
System.out.println();
//输出大根堆
while(max.size()>0) System.out.print(max.poll()+" ");
}
}
/*
输出结果:
0 1 2 2 3 3 5 6 8 9
9 8 6 5 3 3 2 2 1 0
*/