堆实现优先队列

package basicSorted.com;

import java.util.Arrays;

/**
 * @Author Kyrie
 * @Description
 * 二叉堆实现优先队列
 **/
public class Code04_PriorityQueue {

    public static int[] arr;
    public static int size;
    public Code04_PriorityQueue(){
        arr = new int[32];
    }
    //入队
    public static void enQueue(int key){
        if(size >= arr.length){
            resize();
        }
        arr[size++] = key;
        upAdjust();
    }
    //出队
    public static int deQueue() throws Exception{
        if(size <= 0){
            throw new Exception("the queue is empty!");
        }
        int head = arr[0];
        arr[0] = arr[--size];
        downAdjust();
        return head;
    }

    public static void upAdjust(){
        int childIndex = size - 1;  //从数组末尾开始
        int parentIndex = childIndex >>> 1;
        //temp 保存叶子节点的值
        int temp = arr[childIndex];
        while(childIndex > 0 && temp > arr[parentIndex]){
            //优化:无需真正交换,单向赋值即可
            arr[childIndex] = arr[parentIndex];
            childIndex = parentIndex;  //更新childIndex的索引
            parentIndex = parentIndex >>> 1;  //继续找父节点
        }
        //父节点的值小于temp
        arr[childIndex] = temp;
    }

    public static void resize() {
        int newSize = size * 2;
        arr = Arrays.copyOf(arr, newSize);

    }
    public static void downAdjust(){
        int parentIndex = 0;
        //temp的作用相同,用于最后赋值
        int temp = arr[parentIndex];
        int childIndex =  1;
        while(childIndex < size){
            int more = childIndex+1 < size && arr[childIndex+1] > arr[childIndex] ? childIndex+1 : childIndex;

            more = arr[more] > arr[parentIndex] ? more : parentIndex;
            if(parentIndex == more){
                break;  //父节点小于任何一个孩子的值,直接跳出
            }
            //交换
            arr[parentIndex] = arr[more];
            parentIndex = more;
            arr[parentIndex] = temp;
            childIndex = 2 * parentIndex + 1;
        }

    }

    public static void main(String[] args) throws Exception {
        Code04_PriorityQueue queue = new Code04_PriorityQueue();
        enQueue(3);
        enQueue(5);
        enQueue(10);
        enQueue(2);
        enQueue(7);
        System.out.println("出队元素:" + deQueue());
        System.out.println("出队元素:" + deQueue());
        /*
        出队元素:10
        出队元素:7
         */
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值