Java使用PriorityQueue实现小根堆和大根堆

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
*/
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值