Here's my attempt, I believe the runtime is O(V*(ElogE + log E)) since the while loop runs V times and it takes ElogE + log E to do the priority queue operations inside the loop.
class Edge implements Comparable<Edge> {
T source;
T destination;
int weight;
public Edge(T source, T destination, int weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
}
public int compareTo(Edge other) {
return this.weight - other.weight;
}
}
public void printMSTPrims(Map<T, List<Edge> > adjacencyList) {
// Records all visited destinations.
Set<T> visited = new HashSet<>();
Queue<Edge> edges = new PriorityQueue<>();
T currentNode = adjacencyList.entrySet().iterator().next().getKey();
visited.add(currentNode);
// Run until we've visited all vertices
while (visited.size() < adjacencyList.size()) {
// Take all edges from current node and add to the PQ.
for (Edge edge: adjacencyList.get(currentNode)) {
edges.add(edge);
}
// Pick the smallest edge to a destination node not already visited.
Edge edge = edges.remove();
while (!edges.isEmpty() && visited.contains(edge.destination)) {
edge = edges.remove();
}
// Found an eligible edge, print its contents. This edge does not have to necessarily start from the currentNode.
System.out.println(edge.source + "--" + edge.weight + "--" + edge.destination);
// Go next to this destination vertex.
currentNode = edge.destination;
//Now that you've reached this edge as a destination, record it.
visited.add(currentNode);
}
}
PS. I assume the graph does not have self-loops and double-edges.