public static void Main()
Graph graph = CreateGraph(verticesCount, edgesCount);
graph.edge[0].Source = 0;
graph.edge[0].Destination = 1;
graph.edge[0].Weight = 10;
graph.edge[1].Source = 0;
graph.edge[1].Destination = 2;
graph.edge[1].Weight = 6;
graph.edge[2].Source = 0;
graph.edge[2].Destination = 3;
graph.edge[2].Weight = 5;
graph.edge[3].Source = 1;
graph.edge[3].Destination = 3;
graph.edge[3].Weight = 15;
graph.edge[4].Source = 2;
graph.edge[4].Destination = 3;
graph.edge[4].Weight = 4;
public int VerticesCount;
public static Graph CreateGraph(int verticesCount, int edgesCoun)
Graph graph = new Graph();
graph.VerticesCount = verticesCount;
graph.EdgesCount = edgesCoun;
graph.edge = new Edge[graph.EdgesCount];
private static int Find(Subset[] subsets, int i)
if (subsets[i].Parent != i)
subsets[i].Parent = Find(subsets, subsets[i].Parent);
return subsets[i].Parent;
private static void Union(Subset[] subsets, int x, int y)
int xroot = Find(subsets, x);
int yroot = Find(subsets, y);
if (subsets[xroot].Rank < subsets[yroot].Rank)
subsets[xroot].Parent = yroot;
else if (subsets[xroot].Rank > subsets[yroot].Rank)
subsets[yroot].Parent = xroot;
subsets[yroot].Parent = xroot;
private static void Print(Edge[] result, int e)
for (int i = 0; i < e; ++i)
Console.WriteLine("{0} -- {1} == {2}", result[i].Source, result[i].Destination, result[i].Weight);
public static void Kruskal(Graph graph)
int verticesCount = graph.VerticesCount;
Edge[] result = new Edge[verticesCount];
Array.Sort(graph.edge, delegate (Edge a, Edge b)
return a.Weight.CompareTo(b.Weight);
Subset[] subsets = new Subset[verticesCount];
for (int v = 0; v < verticesCount; ++v)
while (e < verticesCount - 1)
Edge nextEdge = graph.edge[i++];
int x = Find(subsets, nextEdge.Source);
int y = Find(subsets, nextEdge.Destination);