Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Kruskal and Prim MST algorithms have different runtimes for sparse and dense graphs?

I am trying to understand why Prim and Kruskal have different time complexities when it comes to sparse and dense graphs. After using a couple of applets that demonstrate how each works, I am still left a little confused about how the density of the graph affects the algorithms. I hope someone could give me a nudge in the right direction.

like image 496
tommy Avatar asked Jan 06 '10 08:01

tommy


People also ask

Why is Prim's algorithm better for dense graphs?

The advantage of Prim's algorithm is its complexity, which is better than Kruskal's algorithm. Therefore, Prim's algorithm is helpful when dealing with dense graphs that have lots of edges. However, Prim's algorithm doesn't allow us much control over the chosen edges when multiple edges with the same weight occur.

Which MST algorithm is better suited for dense graphs and why?

Prim's algorithm is faster when you've got a really dense graph with many more edges than vertices.

Do Prims and Kruskal algorithm give same MST?

For there to be the possibility of multiple MSTs, at least two edges in the graph must be equal. Therefore, the MST is unique, and both Prim's and Kruskal's algorithm will return the same result.


1 Answers

Wikipedia gives the complexity of these algorithms in terms of E, the number of edges, and V, the number of vertices, which is a good practice because it lets you do exactly this sort of analysis.

Kruskal's algorithm is O(E log V). Prim's complexity depends on which data structure you use for it. Using an adjacency matrix, it's O(V2).

Now if you plug in V2 for E, behold you get the complexities that you cited in your comment for dense graphs, and if you plug in V for E, lo you get the sparse ones.

Why do we plug in V2 for a dense graph? Well even in the densest possible graph you can't have as many as V2 edges, so clearly E = O(V2).

Why do we plug in V for a sparse graph? Well, you have to define what you mean by sparse, but suppose we call a graph sparse if each vertex has no more than five edges. I would say such graphs are pretty sparse: once you get up into the thousands of vertices, the adjacency matrix would be mostly empty space. That would mean that for sparse graphs, E ≤ 5 V, so E = O(V).

like image 115
Jason Orendorff Avatar answered Oct 04 '22 13:10

Jason Orendorff