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

后端 未结 10 1368
小鲜肉
小鲜肉 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 05:20

    Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).

提交回复
热议问题