An unbounded priority queue is based on a priority heap
Priority Queue.Offer()
method uses siftUpComparable()
internally to insert items when passed without comparator
siftUpComparable
compares current element with all elements at Parent Positions(int i = paramInt - 1 >>> 1;
) until the Heap condition is met
siftUpComparable
Algorithm in Nutshell (if implemented through array Root=index 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 Code
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;
}
In Your example:
q.offer(4);
-> Inserts 4
Result: PQ[0]=4
q.offer(2);
-> siftUpComparable
compares 4 to 2 and swap positions (comparisons at Parent Locations)
Result: PQ[0]=2,PQ[1]=4
q.offer(8);
-> siftUpComparable
Compares 8 and 2 (since 2 is at Parent Location)
Result: PQ[2]=8
q.offer(6);
: -> siftUp Compares 6 with 4 (Parent of location 3 is Location 1 according to paramInt - 1 >>> 1;
logic )
Result: PQ[3]=6
Final PQ=[2, 4, 8, 6]