time-complexitygraph-theoryminimum-spanning-treekruskals-algorithmprims-algorithm

Understanding when to use Prim or Kruskal for Minimum Spanning Tree


I'm trying to apply Prim's or Kruskal's algorithms to certain situations. I understand that Prim is used when graphs are dense (Example: as adjacency matrix with priority queue as unordered array would be good for a dense tree where E = O(V^2). And Kruskal is used when graphs are sparse (Example: as adjacency list with fast sort where E = O(V). What I'm unsure about is the in between. For example, a graph with a moderate number of edges such that

E = O(V log V)

Would this be Prim or Kruskal? I think it may be either one because Prim O(E log V) and Kruskal O(E log E) have similar time complexities.


Solution

  • Due to the nature of each algorithm, in the case of a graph with moderate number of edges, you should use Kruskal's algorithm. Prim's algorithm runs faster in a graph with many edges as it only compares limited number of edges per loop, where as Kruskal's start by sorting all the edges in the list then going through them again to make check if the edge is part of the minimal spanning tree (MST) or not. So in the case of your question, while both algorithms have similar running time, number of edges in the graph should be the main component when you are deciding between the algorithms. More edges compared to vertices, use Prim's, otherwise, use Kruskal's.