Explain Kruskal's algorithm for shortest path with the help of suitable example.


Q.) Explain Kruskal's algorithm for shortest path with the help of suitable example.

Subject: Data Structures

Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the least possible weight that connects any two trees in the forest. It is a greedy algorithm in graph theory as it finds a minimum spanning tree for a connected weighted graph adding increasing cost arcs at each step. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.

The steps for implementing Kruskal's algorithm are as follows:

  1. Sort all the edges from low weight to high
  2. Take the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle, then reject this edge.
  3. Keep adding edges until we reach all vertices.

Let's illustrate this with an example:

Consider the following graph:

   A---1---B
  / \       \
 4   3       2
/     \       \
C---5---D---6---E

The edges sorted by weight are:

Edge Weight
AB 1
BE 2
AD 3
AC 4
CD 5
DE 6

We start with the edge of least weight, AB. Our tree then looks like this:

A---1---B

Next, we add BE. Our tree then looks like this:

A---1---B
        \
         2
          \
           E

Next, we add AD. Our tree then looks like this:

   A---1---B
  /         \
 3           2
/             \
D              E

Next, we would add AC, but that would create a cycle (A-B-E-D-A), so we reject it.

Next, we add CD. Our tree then looks like this:

   A---1---B
  / \       \
 3   5       2
/     \       \
D---5---C       E

Finally, we would add DE, but that would create a cycle (A-D-C-A), so we reject it.

So, the final minimum spanning tree is:

   A---1---B
  / \       \
 3   5       2
/     \       \
D---5---C       E

The total weight of the tree is 1 + 2 + 3 + 5 = 11.

This is the basic idea of Kruskal's algorithm. It is worth noting that if the graph is not connected, this algorithm will create a minimum spanning forest (a minimum spanning tree for each connected component).