Showing posts with label Kruskal's algorithm implementation using Java. Show all posts
Showing posts with label Kruskal's algorithm implementation using Java. Show all posts

Sunday, 30 December 2012

Kruskal's algorithm's implementation in java

Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph. 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. If the graph is not connected, then it finds a minimum spanning forest (a minimum spanning tree for each connected component).

Example run

ImageDescription
Kruskal Algorithm 1.svgAD and CE are the shortest edges, with length 5, and AD has been arbitrarily chosen, so it is highlighted.
Kruskal Algorithm 2.svgCE is now the shortest edge that does not form a cycle, with length 5, so it is highlighted as the second edge.
Kruskal Algorithm 3.svgThe next edge, DF with length 6, is highlighted using much the same method.
Kruskal Algorithm 4.svgThe next-shortest edges are AB and BE, both with length 7. AB is chosen arbitrarily, and is highlighted. The edge BD has been highlighted in red, because there already exists a path (in green) between B and D, so it would form a cycle (ABD) if it were chosen.
Kruskal Algorithm 5.svgThe process continues to highlight the next-smallest edge, BE with length 7. Many more edges are highlighted in red at this stage: BC because it would form the loop BCEDE because it would form the loop DEBA, and FE because it would form FEBAD.
Kruskal Algorithm 6.svgFinally, the process finishes with the edge EG of length 9, and the minimum spanning tree is found.


import java.io.*; 
class Tnode
{
char label;
//boolean vis;
int prev;
public Tnode(char lab) 
 { 
   label = lab; 
   //vis=false;
   prev=-1;
 } 
}

Best geography books for UPSC prelims, mains

This post is intended to clear the confusion that prevails among the aspirants over how to prepare for UPSC geography and the best books f...