Java优先级队列简单实现

/**
 * 优先级队列简单实现
 * 采用数组实现
 * 插入元素时需要进行key比较,找到索引位置
 * 删除元素时,直接从顶端取出(优先级高的优先处理)
 * @author gisliu
 *
 */
public class PriorityQueue {

    private int MAX_CAPACITY;
    private int[] data;
    private int items;

    public PriorityQueue(int capacity){
        MAX_CAPACITY = capacity;
        data = new int[MAX_CAPACITY];
        items = 0;
    }

    public PriorityQueue(){
        this(10);
    }

    public void insert(int value){
        if(isFull())
            throw new FullQueueException();
        if(items == 0){
            data[items++] = value;
        } else {
//          int j = 0;
//          while(data[j]>value){
//              j++;   // 步骤(1)找到插入的位置
//          }
//
//          for(int i=items;i>j;i--){
//              data[i] = data[i-1];  // 步骤(2)整体移位,腾出一个空间
//          }
//          data[j] = value;

            // 步骤(1)和步骤(2)可以合并
            int i = 0;
            for(i=items-1;i>=0;i--){
                if(data[i] < value) {
                    data[i+1] = data[i];
                } else {
                    break;
                }
            }

            data[i+1] = value;
            items++;
        }
    }

    public int remove(){
        if(isEmpty())
            throw new EmptyQueueException("queue is empty");
        return data[--items];
    }

    public boolean isEmpty(){
        return (items == 0);
    }

    public boolean isFull(){
        return (items == MAX_CAPACITY);
    }

    public int peek(){
        return data[items-1];
    }

    public int size(){
        return items;
    }


    public static void main(String[] args){
        PriorityQueue priority = new PriorityQueue();
        Random random = new Random();
        for(int i=0;i<10;i++){
            priority.insert(random.nextInt(100));
        }

        // 遍历
        for(int i=0;i<10;i++){
            System.out.println(priority.remove());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值