Javatpoint Logo
Javatpoint Logo

Kruskal's Algorithm

Kruskal's Algorithm is used to find the minimum spanning tree for a connected weighted graph. The main target of the algorithm is to find the subset of edges by using which, we can traverse every vertex of the graph. Kruskal's algorithm follows greedy approach which finds an optimum solution at every stage instead of focusing on a global optimum.

The Kruskal's algorithm is given as follows.

Algorithm

  • Step 1: Create a forest in such a way that each graph is a separate tree.
  • Step 2: Create a priority queue Q that contains all the edges of the graph.
  • Step 3: Repeat Steps 4 and 5 while Q is NOT EMPTY
  • Step 4: Remove an edge from Q
  • Step 5: IF the edge obtained in Step 4 connects two different trees, then Add it to the forest (for combining two trees into one tree).
    ELSE
    Discard the edge
  • Step 6: END

Example :

Apply the Kruskal's algorithm on the graph given as follows.


Kruskal's Algorithm

Solution:

the weight of the edges given as :

Edge AE AD AC AB BC CD DE
Weight 5 10 7 1 3 4 2

Sort the edges according to their weights.

Edge AB DE BC CD AE AC AD
Weight 1 2 3 4 5 7 10

Start constructing the tree;

Add AB to the MST;


Kruskal's Algorithm

Add DE to the MST;


Kruskal's Algorithm

Add BC to the MST;


Kruskal's Algorithm
Kruskal's Algorithm

The next step is to add AE, but we can't add that as it will cause a cycle.

The next edge to be added is AC, but it can't be added as it will cause a cycle.

The next edge to be added is AD, but it can't be added as it will contain a cycle.

Hence, the final MST is the one which is shown in the step 4.

the cost of MST = 1 + 2 + 3 + 4 = 10.


C Program:

Output

Enter Nodes and edges5
5
Enter the value of X, Y and edges5 
4
3
Enter the value of X, Y and edges2
3
1
Enter the value of X, Y and edges1
2
3
Enter the value of X, Y and edges5
4
3
Enter the value of X, Y and edges23
3
4
Minimum cost is 11
Next TopicLinear Search




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA