优先级队列的代码实现

package sort;

import java.util.Arrays;
import java.util.Random;

public class PriorityQueue<T extends Comparable<T>> {
    private T[] queue;
    private int index; // 记录有效元素的个数

    public PriorityQueue(){
        this.queue = (T[])new Comparable[10];
    }

    // 入优先级队列
    public void push(T val){
        if(full()){
            this.queue = Arrays.copyOf(queue, queue.length*2);
        }

        if(index == 0){
            queue[index] = val;
        } else {
            siftUp(index, val); // 新插入的元素,要进行堆的上浮操作
        }
        index++;
    }

    /**
     * 堆的上浮函数
     * @param i
     * @param val
     */
    private void siftUp(int i, T val) {
        while(i > 0){
            int j = (i-1)/2;
            if(queue[j].compareTo(val) < 0){
                queue[i] = queue[j];
                i = j;
            } else {
                break;
            }
        }
        queue[i] = val;
    }

    // 出优先级队列
    public T pop(){
        if(empty())
            return null;

        T oldval = queue[0];
        --index;
        if(index > 0){
            siftDown(0, queue[index]); // 删除元素,进行堆的下沉操作
        }
        return oldval;
    }

    /**
     * 堆的下沉函数
     * @param i
     * @param val
     */
    private void siftDown(int i, T val) {
        for(int j=2*i+1; j<index; j=j*2+1){
            if(j+1 < index && queue[j+1].compareTo(queue[j]) > 0){
                j++;
            }

            if(queue[j].compareTo(val) > 0){
                queue[i] = queue[j];
                i = j;
            } else {
                break;
            }
        }
        queue[i] = val;
    }

    boolean full(){
        return index == queue.length;
    }

    boolean empty(){
        return index == 0;
    }

    public static void main(String[] args) {
        PriorityQueue<Integer> que = new PriorityQueue<>();
        Random rd = new Random();
        for (int i = 0; i < 20; i++) {
            que.push(rd.nextInt(100));
        }

        while(!que.empty()){
            System.out.print(que.pop() + " ");
        }
        System.out.println();
         
             }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值