Minimum Spanning Tree Algorithms (Prim's Algorithm, Kruskal's Algorithm)

In graph theory, a minimum spanning tree (MST) is a tree that spans all the vertices of a weighted graph with the minimum possible total edge weight. Minimum spanning tree algorithms are used to find these trees efficiently.

Two well-known algorithms for finding a minimum spanning tree are Prim's algorithm and Kruskal's algorithm. Both algorithms guarantee to find the MST of a given graph, but they differ in their approaches and time complexities.

Prim's Algorithm

Prim's algorithm is a greedy algorithm that starts with an arbitrary vertex and tries to grow the minimum spanning tree by adding the smallest-weighted edge from the current tree to a new vertex. This process is repeated until all vertices are included in the tree.

Here is a step-by-step explanation of Prim's algorithm:

  1. Start with a vertex and initialize an empty tree.
  2. Choose the edge with the smallest weight from the current tree that connects to a vertex not yet in the tree.
  3. Add this edge and the corresponding vertex to the tree.
  4. Repeat steps 2 and 3 until all vertices are included in the tree.

Prim's algorithm can be implemented using a priority queue to efficiently select the smallest-weighted edge at each step. The time complexity of Prim's algorithm is O(E log V), where E is the number of edges and V is the number of vertices.

Kruskal's Algorithm

Kruskal's algorithm is also a greedy algorithm that builds the minimum spanning tree by iteratively adding edges with the smallest weight (without creating a cycle) until all vertices are connected.

Here is a step-by-step explanation of Kruskal's algorithm:

  1. Sort all the edges in the graph based on their weights in non-decreasing order.
  2. Start with an empty tree and initialize a disjoint set data structure.
  3. Iterate through the sorted edges and add an edge to the tree if it does not create a cycle in the current tree.
  4. Repeat step 3 until all vertices are connected.

Kruskal's algorithm requires a disjoint set data structure to efficiently check whether adding a new edge creates a cycle. The time complexity of Kruskal's algorithm is O(E log E), where E is the number of edges.


Both Prim's algorithm and Kruskal's algorithm are efficient ways to find the minimum spanning tree of a weighted graph. Prim's algorithm focuses on growing a tree from a starting vertex, while Kruskal's algorithm builds the tree by repeatedly adding edges with the smallest weight. Depending on the graph characteristics and requirements, one algorithm may be more suitable than the other. Understanding both methods provides valuable tools for solving real-world problems efficiently.

© NoobToMaster - A 10xcoder company