优先队列-Java实现

这篇博客介绍了基于二叉堆实现的优先队列。Hoop类包含了添加元素(add)和删除元素(poll)的方法,以及内部的push和pop辅助方法,确保堆的性质。添加操作将元素添加到数组末尾并向上调整,删除操作则替换根节点并向下调整,保持堆的有序性。

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

   class Hoop {
        int tree[];
        int size;

        public Hoop(int capacity) {
            this.tree = new int[capacity + 1];
            this.size = 1;
        }

        public void add(int val){
            if (size == tree.length + 1) {
                return;
            }
            tree[size] = val;
            push(size);
            size++;
        }

        public int poll() {
            if (size < 1) {
                size = 1;
                return -1;
            }

            int t = tree[1];
            tree[1] = tree[size - 1];
            size--;
            pop(1);
            return t;
        }

        private void push(int index) {
            if (index == 1){
                return;
            }
            int father = index / 2;
            if (tree[index] < tree[father]) {
                int t = tree[index];
                tree[index] = tree[father];
                tree[father] = t;
                push(father);
            }
        }

        private void pop(int idx) {
            if (idx >= tree.length) {
                return;
            }
            int left = 2 * idx;
            int right = 2 * idx + 1;
            int leftVal = left >= size ? Integer.MAX_VALUE : tree[left];
            int rightVal = right >= size ? Integer.MAX_VALUE : tree[right];
            int min = Math.min(tree[idx], Math.min(leftVal, rightVal));
            if (min == tree[idx]) {
                return;
            } else if (min == leftVal) {
                int t = tree[idx];
                tree[idx] = tree[left];
                tree[left] = t;
                pop(left);
            } else {
                int t = tree[idx];
                tree[idx] = tree[right];
                tree[right] = t;
                pop(right);
            }
        }

        public boolean isEmpty() {
            return size == 1;
        }
    }

添加操作:将元素加到数组最后,从下往上与父亲节点找到对应位置
删除操作:将最后一个元素,替代根节点,然后从上往下比较自己与左右孩子组成的三元组,谁最小,直到自身为最小值,结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值