您的位置:首页 > 其它

算法分析——优先队列

2019-07-19 16:28 148 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/Heykeel/article/details/96483551
[code]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;
}
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: