大根堆和小根堆

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

大根堆和小根堆在排序和选择第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() + " ");
        }
    }
}
### 大根堆小根堆的定义 #### 大根堆 大根堆是一种特殊的完全二叉树结构,在这种结构中,任意一个非叶子节点的值都大于或等于其左右子节点的值[^5]。这意味着堆顶(即根节点)始终保存着整个堆中的最大值。 #### 小根堆 小根堆同样是基于完全二叉树的一种特殊结构,但在该结构中,任意一个非叶子节点的值都小于或等于其左右子节点的值[^4]。因此,堆顶(即根节点)保存的是整个堆中的最小值。 --- ### 大根堆小根堆的区别 两者的根本区别在于它们维护的性质不同: 1. **节点大小关系** - 在大根堆中,父节点的值总是大于或等于子节点的值。 - 在小根堆中,父节点的值总是小于或等于子节点的值。 2. **堆顶元素特性** - 对于大根堆而言,堆顶元素是整个堆中的最大值。 - 对于小根堆来说,堆顶元素则是整个堆中的最小值。 3. **应用场景差异** - 大根堆通常用于寻找集合中的最大值或者构建优先队列时需要处理高优先级的任务。 - 小根堆则适用于寻找集合中的最小值以及某些特定场景下的最短路径计算等问题。 以下是两种堆的一个简单实现示例: ```python # 大根堆插入操作演示 def heap_insert_max(heap, value): heap.append(value) index = len(heap) - 1 while index > 0: parent_index = (index - 1) // 2 if heap[parent_index] >= heap[index]: break heap[parent_index], heap[index] = heap[index], heap[parent_index] index = parent_index # 小根堆插入操作演示 def heap_insert_min(heap, value): heap.append(value) index = len(heap) - 1 while index > 0: parent_index = (index - 1) // 2 if heap[parent_index] <= heap[index]: break heap[parent_index], heap[index] = heap[index], heap[parent_index] index = parent_index # 测试代码 max_heap = [] min_heap = [] heap_insert_max(max_heap, 10) heap_insert_max(max_heap, 20) heap_insert_max(max_heap, 15) heap_insert_min(min_heap, 10) heap_insert_min(min_heap, 20) heap_insert_min(min_heap, 15) print("Max Heap:", max_heap) # 输出应为 [20, 10, 15] print("Min Heap:", min_heap) # 输出应为 [10, 20, 15] ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值