13,797,342 members
Add your own
alternative version

#### Stats

135.6K views
10.5K downloads
70 bookmarked
Posted 1 Mar 2011
Licenced CPOL

# Kruskal Algorithm

, 5 Jul 2012
Implementation of Kruskal Algorithm in C#

## Introduction

According to Wikipedia:"Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connectedweighted 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). Kruskal's algorithm is an example of a greedy algorithm."

In short, Kruskal's algorithm is used to connect all nodes in a graph, using the least cost possible.

#### Example

A cable TV company is laying a cable in a new neighborhood. An internet cafe is connecting all PCs via network.

## Using the Demo

Click anywhere to plot the vertices. Hold down ctrl and select two vertices to create an edge. A popup window appears to enter edge cost. Having finished plotting the graph, click Solve.

## Using the Code

`IList<Edge> Solve(IList<Edge> graph, out int totalCost);  `

How the Graph is formed with GDI is not covered as it is irrelevant.

## Classes

Typically, our graph consists of two components, Vertices, and Edges connecting these vertices.

Each Edge is marked by a value or weight, which is the Cost of connecting the two vertices.

### Vertex

Holds:

• Vertex Name (which must be unique within Graph) and its Drawing Point
• Rank and Root (we'll get to those later)
```using System;
using System.Drawing;

namespace Kruskal
{
public class Vertex
{
#region Members

private int name;

#endregion

#region Public Properties

public int Name
{
get
{
return name;
}
}

public int Rank { get; set; }

public Vertex Root { get; set; }

public Point Position { get; set; }

#endregion

#region Constructor

public Vertex(int name, Point position)
{
this.name = name;
this.Rank = 0;
this.Root = this;
this.Position = position;
}

#endregion

#region Methods

internal Vertex GetRoot()
{
if (this.Root != this)// am I my own parent ? (am i the root ?)
{
this.Root = this.Root.GetRoot();// No? then get my parent
}

return this.Root;
}

internal static void Join(Vertex root1, Vertex root2)
{
if (root2.Rank < root1.Rank)//is the rank of Root2 less than that of Root1 ?
{
root2.Root = root1;//yes! then Root1 is the parent of Root2 (since it has the higher rank)
}
else //rank of Root2 is greater than or equal to that of Root1
{
root1.Root = root2;//make Root2 the parent
if (root1.Rank == root2.Rank)//both ranks are equal ?
{
root2.Rank++;//increment Root2, we need to reach a single root for the whole tree
}
}
}

#endregion
}
} ```

### Edge

Holds two Vertices, Cost of connection between them, and CostDrawing Point.

Note that it implements `IComparable`, we'll need it to sort Edges by Cost later on.

```using System;
using System.Drawing;

namespace Kruskal
{
public class Edge : IComparable
{
#region Members

private Vertex v1, v2;
private int cost;
private Point stringPosition;

#endregion

#region Public Properties

public Vertex V1
{
get
{
return v1;
}
}

public Vertex V2
{
get
{
return v2;
}
}

public int Cost
{
get
{
return cost;
}
}

public Point StringPosition
{
get
{
return stringPosition;
}
}

#endregion

#region Constructor

public Edge(Vertex v1, Vertex v2, int cost, Point stringPosition)
{
this.v1 = v1;
this.v2 = v2;
this.cost = cost;
this.stringPosition = stringPosition;
}

#endregion

#region IComparable Members

public int CompareTo(object obj)
{
Edge e = (Edge)obj;
return this.cost.CompareTo(e.cost);
}

#endregion
}
} ```

## Algorithm Implementation

### Sorting Edges

Edges are sorted in ascending order according to Cost using Quick Sort.

### Making Sets

Initially, every Vertex is its own Root and has rank zero.

```public Vertex(int name, Point position)
{
this.name = name;
this.Rank = 0;
this.Root = this;
this.Position = position;
}
```

## Why This Step?

We need it to ensure that, on adding our Vertices, we are not forming a loop.

Consider this example:

The Edge BD was not considered, because B,D are already connected through B,A,D.

Thus, for every Edge we examine, we must inspect that its two Vertices belong to different sets (trees).

## How To Find Out If Two Vertices Are In Different Sets?

Using the recursive function `GetRoot()`.

```internal Vertex GetRoot()
{
if (this.Root != this)// am I my own parent ? (am i the root ?)
{
this.Root = this.Root.GetRoot();// No? then get my parent
}

return this.Root;
} ```

If roots are indeed different, (each Vertex is in a different set), `Join()` the two Vertices.

```internal static void Join(Vertex root1, Vertex root2)
{
if (root2.Rank < root1.Rank)//is the rank of Root2 less than that of Root1 ?
{
root2.Root = root1;//yes! then Root1 is the parent of Root2 (since it has the higher rank)
}
else //rank of Root2 is greater than or equal to that of Root1
{
root1.Root = root2;//make Root2 the parent
if (root1.Rank == root2.Rank)//both ranks are equal ?
{
root2.Rank++;//increment Root2, we need to reach a single root for the whole tree
}
}
} ```

## Conclusion

Hope I delivered a clear explanation.

## License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

## About the Author

 Software Developer Egypt
Enthusiastic programmer/researcher, passionate to learn new technologies, interested in problem solving, data structures, algorithms, AI, machine learning and nlp.

Amateur guitarist/ keyboardist, squash player.

## Comments and Discussions

 First PrevNext
 Feedback jon-802-Dec-15 2:35 jon-80 2-Dec-15 2:35
 Interesting program, however I could not quite understand how the algorithm works, as when solving a simple network no results are displayed. Why is the cost not allowing a fraction of an integer (decimal) to be inputted? It would be nice if this URL ()[^], allowed me to update a screenshot to illustrate my specific scenario. This has been posted to https://www.facebook.com/camilleri.jon[^] (Add me as a friend if you wish my nome de plume is John Smith ) What I did was a simple network between (0) and (1) with a single edge that has a cost of 1. Clicking Solve does not have any evident results on the algorithm, so I have no idea what it does without reading the code, perhaps more visual interaction would help me understand better. After a second try I tried a more complicated network and I realized that the algorithm adds up the cost of the edges according to the values inputted by the user. I hope that in the future we find real world applications where theory can be applied to our pool of knowledge in our pursuit of data and computer science, therefore, I am providing some links herewith. References 1. [^] 2. Graph theory - .[^] 3. Maarten Van Steen, Graph Theory and Complex Networks - .[^], as was suggested by our prof at the University of Malta ()[^] Jonmodified 2-Dec-15 7:52am.
 You are awesome!! Member 120365086-Oct-15 1:48 Member 12036508 6-Oct-15 1:48
 may be a stupid question... Member 116639895-May-15 10:02 Member 11663989 5-May-15 10:02
 My vote of 5 phoenix05295-Dec-14 0:34 phoenix0529 5-Dec-14 0:34
 Edges Member 106370692-Mar-14 7:14 Member 10637069 2-Mar-14 7:14
 Re: Edges Member 1080906410-May-14 9:15 Member 10809064 10-May-14 9:15
 KRUSKAL ALGORITM EASY IMPLENTATION For A BEginer Learner Member 104879102-Jan-14 11:08 Member 10487910 2-Jan-14 11:08
 Great article, Go 5! The Manoj Kumar21-Nov-13 9:13 The Manoj Kumar 21-Nov-13 9:13
 Re: Great article, Go 5! Omar Gameel Salem21-Nov-13 22:44 Omar Gameel Salem 21-Nov-13 22:44
 This is a masterpiece ThirstyMind13-Oct-13 7:21 ThirstyMind 13-Oct-13 7:21
 Re: This is a masterpiece Omar Gameel Salem13-Oct-13 7:34 Omar Gameel Salem 13-Oct-13 7:34
 aaa Member 102258431-Oct-13 21:35 Member 10225843 1-Oct-13 21:35
 What compiler you use?? thanks :) Afdolol10-May-13 0:09 Afdolol 10-May-13 0:09
 Re: What compiler you use?? thanks :) Omar Gameel Salem10-May-13 3:53 Omar Gameel Salem 10-May-13 3:53
 My vote of 5 Kenneth Haugland11-Aug-12 0:00 Kenneth Haugland 11-Aug-12 0:00
 My vote of 5 Abinash Bishoyi6-Apr-12 4:05 Abinash Bishoyi 6-Apr-12 4:05
 My vote of 5 Manoj Kumar Choubey28-Mar-12 0:44 Manoj Kumar Choubey 28-Mar-12 0:44
 My Vote of 5 RaviRanjanKr30-Dec-11 5:58 RaviRanjanKr 30-Dec-11 5:58
 Re: My Vote of 5 mobilat30-Dec-11 7:39 mobilat 30-Dec-11 7:39
 Quick sort mobilat28-Dec-11 23:48 mobilat 28-Dec-11 23:48
 My vote of 5 al13n9-Oct-11 22:42 al13n 9-Oct-11 22:42
 Some responses to unjustified criticisms [modified] AndyUk0611-Sep-11 5:02 AndyUk06 11-Sep-11 5:02
 Re: Some responses to unjustified criticisms Omar Gameel Salem11-Sep-11 5:09 Omar Gameel Salem 11-Sep-11 5:09
 Re: Some responses to unjustified criticisms AndyUk0611-Sep-11 7:52 AndyUk06 11-Sep-11 7:52
 My vote of 5 AndyUk069-Sep-11 2:01 AndyUk06 9-Sep-11 2:01
 Last Visit: 12-Dec-18 22:59     Last Update: 12-Dec-18 22:59 Refresh 12 Next »

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.181207.3 | Last Updated 5 Jul 2012
Article Copyright 2011 by Omar Gameel Salem
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid