大根堆和小根堆

本文通过一个Java实例展示了如何使用优先队列实现大根堆和小根堆,并演示了这两种堆结构如何进行基本的操作如添加元素和移除元素。通过具体数组操作的例子,读者可以直观地看到堆排序的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大根堆和小根堆在排序和选择第K大的数中经常有用到。
在这里插入图片描述
在Java中是可以直接实现这两个中结构的,使用的优先队列

public class TIMU1 {

    //小根堆
    public PriorityQueue<Integer> minHead = new PriorityQueue<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1 - o2;
        }
    });

    //大根堆
    public PriorityQueue<Integer> maxHead = new PriorityQueue<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });

    public static void main(String[] args) {
        TIMU1 ti = new TIMU1();
        int[] arr = {2,9,4,7,3,6};

        for(int i : arr){
            ti.minHead.add(i);
            ti.maxHead.add(i);
        }

        while(!ti.minHead.isEmpty() ){
            System.out.print(ti.minHead.poll() + " ");
        }
        System.out.println();
        while(!ti.maxHead.isEmpty()){
            System.out.print(ti.maxHead.poll() + " ");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值