算法分析——优先队列

public class PriorityQueue
{
    // 最小堆
    public PriorityQueue(int max)
    {
        this.heap = new int[max + 2];
        this.max = max + 1;
    }
    
    // 维护的堆数据
    private int[] heap;

    // 优先队列的最大容量
    private int max;

    // 队列指针
    private int capacity = 0;
    
    // 插入数据
    public void insert(int key)
    {
        this.heap[++this.capacity] = key;
        swim(capacity);
        
        if (capacity == this.max)
        {
            this.deleteMin();
        }
    }
    
    // 删除最小值
    public int deleteMin()
    {
        int min = this.heap[1];
        this.heap[1] = this.heap[capacity];
        this.heap[capacity--] = 0;
        sink(1);
        return min;
    }
    
    // 上浮
    private void swim(int k)
    {
        while (k > 1)
        {
            if (less(this.heap[k], this.heap[k / 2]))
            {
                swap(k, k / 2, this.heap);
            }
            k /= 2;
        }
    }
    
    // 下沉
    private void sink(int k)
    {
        while (2 * k < this.capacity)
        {
            int j = 2 * k;
            if (j < this.capacity && less(this.heap[j+1], this.heap[j]))
            {
                j++;
            }
            swap(k, j, this.heap);
            k = j;
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值