5

I am adding edges to a PriorityQueue but for some reason they do not get sorted by their value, leading to a faulty result later.

My edge class looks like this

class Edge implements Comparable<Edge>{
int value;
String dest;
String start;

public Edge(String start, String dest, int g) {
    this.dest = dest;
    value = g;
    this.start = start;
}
@Override
public int compareTo(Edge o) {
    int temp = value - o.value;
    if (temp > 0) {
        return 1;
    }
    if (temp < 0) {
        return -1;
    }
    return 0;
}

Yet, when I run my code where I do addAll on a LinkedList belonging to the Node "Springfield, MO" to the PriorityQueue, the Edges get sorted in the wrong order as seen below, what is the issue?

queue.addAll(list.get(node));

enter image description here

I have tried to make a specific comparator class for Edge and using it as a parameter in the PriorityQueue but I still get the same result.

Slayahh
  • 373
  • 4
  • 14

1 Answers1

8

The internal structure of the PriorityQueue is not ordered, it is a heap, you can check this question.

When you retrieve data using method peek or poll, it is guranteed to be ordered.

But be careful when you iterator the queue:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

xingbin
  • 27,410
  • 9
  • 53
  • 103
  • Sorry but can you elaborate? Does the iteration in addAll not use the comparator when adding the elements into the PriorityQueue? – Slayahh May 03 '18 at 12:07
  • @Slayahh No, the internal structure of the queue is not ordered. It is based on a heap. – xingbin May 03 '18 at 12:10
  • But wouldn't that mean that I have to call sort() every time I added a new element to the queue? Doesn't that diminish the point of a priorityqueue if it doesnt sort the one element that is added? – Slayahh May 03 '18 at 12:16
  • @Slayahh You can retrieve element one by one from the queue, you are guranteed to get ordered data. – xingbin May 03 '18 at 12:17
  • Actually, the internal structure of the queue *is* ordered. It's just not *sorted*. – Jim Mischel May 05 '18 at 06:56
  • @Jim Mischel, please clarify. What do you mean when you say the queue is ordered but not sorted. – GilbertS Apr 04 '20 at 15:39
  • 1
    @GilbertS The queue is in heap order, which is not necessarily sorted order. For example, the internal order might be `[1,3,2,6,5,4]`. That's in heap order. It's obviously not *sorted*, though. – Jim Mischel Apr 04 '20 at 16:22