for (Event e : pq)
doesn't iterate in the priority order.
while(!pq.isEmpty()){
Event e = pq.poll();
}
This works but empties the queue.
for (Event e : pq)
doesn't iterate in the priority order.
while(!pq.isEmpty()){
Event e = pq.poll();
}
This works but empties the queue.
From the Javadocs:
There are probably other equivalent mechanisms.
A heap based priority queue only guarantees that the first element is the highest/lowest. There is no cheap (i.e. O(n)) way to get the elements in sorted form.
If you need to do this often, consider using a structure that maintains the elements in sorted form. For example, use
java.util.TreeSet
, and use eitherpollFirst()
orpollLast()
in place ofpeek()
/poll()
So taking the priorityQueue in a List and then sorting it is a good option as mentioned above. Here are some details why the iterator gives unexpected results:
The iterator does not return elements in the correct order because it prints from the underlying data structure (similar to ArrayList). The ArrayList has data stored in it in the same way the data is stored in an Array implementation of BinaryHeap. For example:
where childOf(i) is 2*i+1 and 2*i+2 and parentOf(i) is (i-1)/2