Assigment No 3
Assigment No 3
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
graphEdges.sort(new Comparator<Edge>() {
@Override public int compare(Edge o1, Edge o2)
{
return o1.weight - o2.weight;
}
});
kruskals(V, graphEdges);
}
private static void kruskals(int V, List<Edge> edges)
{
int j = 0;
int noOfEdges = 0;
Subset subsets[] = new Subset[V];
Edge results[] = new Edge[V];
for (int i = 0; i < V; i++) {
subsets[i] = new Subset(i, 0);
}
while (noOfEdges < V - 1) {
// Pick the smallest edge. And increment
// the index for next iteration
Edge nextEdge = edges.get(j);
int x = findRoot(subsets, nextEdge.src);
int y = findRoot(subsets, nextEdge.dest);
if (x != y) {
results[noOfEdges] = nextEdge;
union(subsets, x, y);
noOfEdges++;
}
j++;
}
System.out.println(
"Following are the edges of the constructed MST:");
int minCost = 0;
for (int i = 0; i < noOfEdges; i++) {
System.out.println(results[i].src + " -- "
+ results[i].dest + " == "
+ results[i].weight);
minCost += results[i].weight;
}
System.out.println("Total cost of MST: " + minCost);
}
private static void union(Subset[] subsets, int x,
int y)
{
int rootX = findRoot(subsets, x);
int rootY = findRoot(subsets, y);
subsets[i].parent
= findRoot(subsets, subsets[i].parent);
return subsets[i].parent;
}
}
Output: