The strategy is to make the disjoint sets grow using the lowest edges possible at each time.
THE KEY: We use the parents array. Each slot in parent array represents the representative node for the groups formed for each node.
public class KruskalMST {
// Finds the REPRESENTING NODE for vertex i
static int find(int i, int[] parent)
{
while (parent[i] != i)
i = parent[i];
return i;
}
// Does union of i and j.
static void union1(int i, int j, int[] parent)
{
//find representatives of;
//i --> a
//and
//j --> b
int a = find(i, parent);
int b = find(j, parent);
//make the representative of a point to representative of j
parent[a] = b;
}
// Finds MST using Kruskal's algorithm
static int kruskalMST(int cost[][])
{
int V = cost.length;
int[] parent = new int[V];
int INF = Integer.MAX_VALUE;
int mincost = 0; // Cost of min MST.
// Initialize sets of disjoint sets.
for (int i = 0; i < V; i++)
parent[i] = i;
// Include minimum weight edges one by one
int edge_count = 0;
while (edge_count < V - 1)
{
int min = INF, a = -1, b = -1;
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (find(i, parent) != find(j, parent) && cost[i][j] < min)
{
min = cost[i][j];
a = i;
b = j;
}
}
}
union1(a, b, parent);
edge_count++;
mincost += min;
}
return mincost;
}
}
}