优先队列(堆)

普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。通常采用堆数据结构来实现。

入队列:
1)首先按尾插方式将数据插入数组;
2)比较其和其双亲的值的大小,如果双亲的值大,则满足优先队列的性质,插入结束;
3)否则,交换其和双亲的位置的值,重新进行2,3步;
4)直到根节点.
出队列:
为了不破坏优先队列的性质,不能直接删除队首元素,应该先用数组的最后一个元素替换队首元素,再通过向下调整重新构成优先队列.
返回队首元素:
直接返回队首元素.

package test1124.MyPriorityQueue;

public class MyPriorityQueue {
    private int[] array = new int[100];
    private int size = 0;
    //向上调整队列
    public void shiftUp(int[] array, int index){
        while (index > 0){
            int parent = (index - 1) / 2;
            if (array[index] <= array[parent]){
                break;
            }
                swap(array,index,parent);
                index = parent;
        }
    }

    //交换队列元素
    public static void swap(int[] array, int x, int y){
        int temp = array[x];
        array[x] = array[y];
        array[y] = temp;
    }

    //向下调整
    public void shiftDown(int[] array, int size, int index){
        int parent = index;
        int child = 2 * parent + 1;
        while (child < size){
            if (child + 1 < size && array[child] < array[child + 1]){
                child  = child + 1;
            }

            if (array[parent] > array[child]){
                break;
            }
            swap(array,child,parent);
            parent = child;
            child = 2 * parent + 1;
        }
    }
    //入队
    public void offer(int x){
        //处理队列已满的情况
        if (size >= array.length){
            return;
        }

        array[size] = x;
        size++;
        shiftUp(array,size - 1);
    }

    //出队
    public Integer poll(){
        //处理队为空的情况
        if (size == 0){
            return null;
        }

        int ret = array[0];
        array[0] = array[size - 1];
        shiftDown(array,size,0);
        return ret;
    }

    //返回队首元素
    public Integer peek(){
        //处理队为空的情况
        if (size == 0){
            return null;
        }
        //返回队首元素
        return array[0];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值