Search code examples
javapriority-queue

Priority Queue<Integer>=k ,does not remove the k where distance[k] is min


int[] distance = new int[100];
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        if (distance[o1] > distance[o2] ) {
            return -1;
        } else if (distance[o1] < distance[o2] ) {
            return 1;
        }
        return 0;
    }
});


for (int i = 0; i < 100; i++) {
    distance[i] =new Random().nextInt(100)+1;
    pq.add(i);
}

distance[10]=0;
int u=pq.poll();

I thought this comparator should return the element k which distance[k]=MinimumDistance. Cant Understand why this isn't working.. pq.Poll it's not based on distance[] array. For example here variable u should be 10.


Solution

  • Two issues: Your comparison is reversed. It should be

    if (distance[o1] > distance[o2] ) {
        return 1;
    } else if (distance[o1] < distance[o2] ) {
        return -1;
    }
    

    Second, you have to set distance[10]=0 before the loop and then not overwrite it. This comparator only comes into play while adding stuff and then you have a random number at position 10.