Search code examples
javacollectionspriority-queuecomparatorcomparable

Comparator class implementation for priority queue used in Dijkstra's Algorithm?


I'm trying to implement Dijsktra's Algorithm from CLRS - Introduction to Algorithms book,however, i'm having trouble about implementing a priority queue with Comparator interface. This is my Vertex class as you can see;

public class Vertex {

    public boolean explored;
    public int vertexID;
    public LinkedList<Vertex> adjacencyList;
    public LinkedList<Edge> edgeSet;
    public int shortestDistance;
    public Vertex predecessor;

    public Vertex(int vertexID){

        this.vertexID = vertexID;
        this.explored = false;
        this.adjacencyList = new LinkedList<>();
        this.edgeSet = new LinkedList<>();
        this.shortestDistance = Integer.MAX_VALUE;
        this.predecessor = null;
    }
}

So initially shortestDistance attribute is declared to Integer.MAX_VALUE. Furthermore, you can see the class which implements from Comparator, is used for priority queue.

public class WeightComparator implements Comparator<Vertex> {

    @Override
    public int compare(Vertex o1, Vertex o2) {

        return Math.min(o1.shortestDistance, o2.shortestDistance);
    }
}

I'm sure that the whole implementation doesn't have any logical errors due to my some tests,however, in some tests it fails. I create a reference to my queue with this statement

PriorityQueue<Vertex> queue = new PriorityQueue<>(N, weightComparator);

where N is the size of the queue. So please correct me if i'm wrong about the way how it works. When you poll an item from it, it will remove the item which has least priority ?. Hope it had been clear to understand my problem, and i will appreciate a lot if anyone can help about this. So thanks anyway


Solution

  • Math.min gives you the smaller of two values. Returning that as a compare value is wrong.

    A compare return value of <0 means the first value is smaller than the second, but if you return Math.Min(5, 3), you will get 3, which is >0, which means that the comparator will tell it that 3 > 5. Which is wrong.

    What you are looking for is:

    public int compare(Vertex o1, Vertex o2) {
        return Integer.compare(o1.shortestDistance, o2.shortestDistance);
    }