When should I use Kruskal as opposed to Prim (and vice versa)?

后端 未结 10 1386
小鲜肉
小鲜肉 2020-12-04 04:27

I was wondering when one should use Prim\'s algorithm and when Kruskal\'s to find the minimum spanning tree? They both have easy logics, same worst cases, and only differenc

10条回答
  •  天命终不由人
    2020-12-04 04:56

    Use Prim's algorithm when you have a graph with lots of edges.

    For a graph with V vertices E edges, Kruskal's algorithm runs in O(E log V) time and Prim's algorithm can run in O(E + V log V) amortized time, if you use a Fibonacci Heap.

    Prim's algorithm is significantly faster in the limit when you've got a really dense graph with many more edges than vertices. Kruskal performs better in typical situations (sparse graphs) because it uses simpler data structures.

提交回复
热议问题