Prim's algorithm, using a priority queue

5.2k views Asked by At

I'm trying to implement prim's algorithm, using a priority queue. When I call offer() method, it gives me a class cast exception, saying that vertex cannot be cast to comparable. Is there a workaround?

public static Collection<Edge> prims(Graph g, int start) {
            ArrayList<Edge> mst = new ArrayList<Edge>();
            PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>();
            Vertex startVertex;

        for (Vertex vertex : g.getVertices()) {
            vertices.offer(vertex);
            if (vertex.getId() == start) {
                startVertex = vertex;
            }
        }

        if (!mst.isEmpty()) {
            return mst;
        }

        return null;
    }
}
3

There are 3 answers

0
OldCurmudgeon On BEST ANSWER

Prims algorithm uses the weight of the edge to determine the best path. Posting the vertex to the PriorityQueue will not work.

I am guessing your Edge class will implement Comparable by comparing their lengths.

0
chiastic-security On

Yes: you need your Vertex method to implement Comparable<Vertex>.

Java's PriorityQueue is an implementation of a heap, which has log-time insertion, and log-time removal of the minimum element. But in order for that to be meaningful, you need to have a notion of minimum; and that means you need whatever you put into a PriorityQueue to be Comparable, so that two elements in the heap can be compared.

The reason that non-Comparable elements can be inserted into a PriorityQueue is that you can also specify a Comparator in the constructor, rather than using Comparable elements. So as an alternative, you could leave your Vertex class as it is, but use the appropriate constructor (which also requires you to specify an initial capacity):

PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>(11,
    new Comparator<Vertex>() {
        //implement .compare() and .equals()
    });
1
peter.petrov On

The solution is to have your Vertex class implement Comparable, or to provide a Comparator to the priority queue when constructing it. The Java collections framework needs a way to compare your vertices (after all you're putting them into a priority queue and priority implies the necessity of some ordering being present).