一个无边界的优先级队列基于优先级堆
Priority Queue.Offer()
方法在没有比较器的情况下内部使用siftUpComparable()
插入项。
siftUpComparable
将当前元素与父位置(int i = paramInt - 1 >>> 1;
)的所有元素进行比较,直到满足堆条件为止。
siftUpComparable
算法概述(如果通过数组实现,根节点为索引0):
1.Add the element to the bottom level of the heap.
2.Compare the added element with its parent; if they are in the correct order, stop.
3.If not, swap the element with its parent and return to the previous step.
Java 代码
private void siftUpComparable(int paramInt, E paramE)
{
Comparable localComparable = (Comparable)paramE;
while (paramInt > 0)
{
int i = paramInt - 1 >>> 1;
Object localObject = this.queue[i];
if (localComparable.compareTo(localObject) >= 0) {
break;
}
this.queue[paramInt] = localObject;
paramInt = i;
}
this.queue[paramInt] = localComparable;
}
在您的示例中:
q.offer(4); -> 插入4
结果:PQ[0]=4
q.offer(2);
-> siftUpComparable
将4和2进行比较并交换位置(在父节点位置进行比较)
结果:PQ[0]=2,PQ[1]=4
q.offer(8);
-> siftUpComparable
比较8和2(因为2在父节点位置)
结果: PQ[2]=8
q.offer(6);
: -> siftUp 将6与4进行比较(根据paramInt - 1 >>> 1;
逻辑,位置3的父节点是位置1),进行上滤操作。
Result: PQ[3]=6
最终
PQ=[2, 4, 8, 6]
。