Example Query and Response
(The links to relevant wiki pages are shown in blue)
What is the difference between Prim's and Kruskal's algorithm?
According to the wiki, the primary differences between Prim's and Kruskal's algorithms for finding a minimum-spanning-tree (MST) are their underlying strategies and performance characteristics:
1Fundamental Strategy
- Prim's Algorithm is vertex-centric. It grows a single tree from an arbitrary starting vertex, adding the least-cost edge that connects a vertex in the tree to one outside the tree at each step (L9-minimum-spanning-tree-prim).
- Kruskal's Algorithm is edge-centric. It builds a "forest" by sorting all edges by weight and adding the shortest edge that does not form a cycle, eventually merging separate components into a single tree (L10-minimum-spanning-tree-kruskal).
2Efficiency and Graph Density
The choice between the two often depends on the graph's density (mst-algorithms):
- Prim's is generally better for dense graphs (where E ≈ V²). Its basic complexity is O(V²), though it can be improved to O(E + V log V) using Fibonacci Heaps.
- Kruskal's is generally better for sparse graphs (where E is closer to V). Its complexity is O(E log E) or O(E log V), which is dominated by the initial sorting of edges.
3Implementation and Data Structures
- Prim's relies on a Priority Queue (min-heap) to efficiently find the next vertex to add to the growing tree (mst-algorithms).
- Kruskal's requires Disjoint Set Union (Union-Find) with path compression and union by rank to efficiently check for cycles as edges are added (L10-minimum-spanning-tree-kruskal, mst-algorithms).
4Specialized Applications
- Kruskal's MST can be used as a heuristic for the Travelling Salesman Problem (TSP); a tour created by traversing the MST is guaranteed to be less than twice the length of the optimal TSP tour (L10-minimum-spanning-tree-kruskal).