介绍一下PriorityQueue的堆排序三种常见用法

public class PriorityQueueDemo {
    public static void main(String[] args) {
        // 创建小顶堆(默认)
        System.out.println("=== 小顶堆示例 ===");
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        
        // 添加元素
        minHeap.offer(5);
        minHeap.offer(1);
        minHeap.offer(10);
        minHeap.offer(3);
        
        System.out.println("小顶堆出队顺序:");
        while (!minHeap.isEmpty()) {
            System.out.print(minHeap.poll() + " ");  // 输出:1 3 5 10
        }
        
        System.out.println("\n\n=== 大顶堆示例 ===");
        // 使用Comparator创建大顶堆
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
        
        maxHeap.offer(5);
        maxHeap.offer(1);
        maxHeap.offer(10);
        maxHeap.offer(3);
        
        System.out.println("大顶堆出队顺序:");
        while (!maxHeap.isEmpty()) {
            System.out.print(maxHeap.poll() + " ");  // 输出:10 5 3 1
        }
        
        System.out.println("\n\n=== 字符串优先队列 ===");
        PriorityQueue<String> stringQueue = new PriorityQueue<>();
        
        stringQueue.offer("banana");
        stringQueue.offer("apple");
        stringQueue.offer("cherry");
        
        System.out.println("字符串小顶堆出队顺序:");
        while (!stringQueue.isEmpty()) {
            System.out.print(stringQueue.poll() + " ");  // 按字典序输出
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值