ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Kruskal algorithm implementation in C

Updated on September 19, 2011

Kruskal Algorithm

Kruskal Algorithm

Kruskal's algorithm is an 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). Kruskal's algorithm is an example of a greedy algorithm.


  • create a forest F (a set of trees), where each vertex in the graph is a separate tree
  • create a set S containing all the edges in the graph
  • while Sis nonemptyand F is not yet spanning
    • remove an edge with minimum weight from S
    • if that edge connects two different trees, then add it to the forest, combining two trees into a single tree
    • otherwise discard that edge.

At the termination of the algorithm, the forest has only one component and forms a minimum spanning tree of the graph.

C source code

#include<stdio.h>

#include<stdlib.h>

void printArray(int a[][100],int n);

void AdjacencyMatrix(int a[][100], int n){
	int i,j;
	for(i = 0;i < n; i++)
	{
		for(j = 0;j < i; j++)
		{
			a[i][j] = a[j][i]= rand()%50;
			if( a[i][j]>40)a[i][j]=a[j][i]=999;
			
		}
	a[i][i] = 999;
	}
	printArray(a,n);
}

void printArray(int a[][100],int n){
	int i,j;
	for(i=0;i<n;i++)
	{
		for(j=0;j<n;j++)
		{
			printf("%d\t",a[i][j]);
		}
		printf("\n");
	}
}

int root(int v,int p[]){

	while(p[v] != v)
		{v = p[v];}
		
return v;
}

void union_ij(int i,int j,int p[]){
	if(j > i)
		p[j] = i;
	else
		p[i] = j;
}

void kruskal(int a[][100],int n){
	int count, i, p[100], min, j, u, v, k, t[100][100], sum;
	count = k = sum = 0;
	for(i = 0; i < n; i++)
	{
		p[i] = i;
	}
	while(count < n)
	{
		min = 999;
		for(i = 0; i < n; i++)
		{
			for(j = 0;j < n; j++)
			{
			
				if(a[i][j] < min)
				{
					min = a[i][j];
					u = i;
					v = j;
					
				}
			}
		}
 		if(min != 999)
		{
			i = root(u, p);
			j = root(v, p);
			if (i != j)
			{
				t[k][0] = u;
				t[k][1] = v;
				
				k++;
				
				sum += min;
				union_ij(i,j,p);
			}
		a[u][v] = a[v][u] = 999;
		
		}count +=1;
	}	
	if(count != n)
	{
		printf("spanning tree not exist\n");
	}
	if(count == n)
	{
		printf("Adges Spanning tree is\n");
		for(k = 0; k < n-1 ; k++)
		{
			printf(" %d -> %d ",t[k][0],t[k][1]);
		}
	printf("\ncost = %d \n",sum);
	}
}

int main()
{
	int a[100][100],n;
	printf("enter the number of vertices\n");
	scanf("%d",&n);
	AdjacencyMatrix(a,n);
	kruskal(a,n);
	return 0;
}
	

Content of Makefile

a.out:	kruskal.c
	gcc kruskal.c
	
PHONY:clean
clean:
	rm *~ a.out

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      bfilipek 

      4 years ago

      It would be better if you provide some more examples and description. Graph algorithms are quite hard to understand so the more examples the better person can understand the idea.

    • profile image

      gohil binal 

      5 years ago

      thnx

    • profile image

      play 

      6 years ago

      good post :) thanks for help

    • profile image

      ezhisai 

      6 years ago

      this was more useful and effective examples.from this, i am full understood.

    • profile image

      rajesh subramanian 

      6 years ago

      Ankit is exactly right! we might build a heap to reduce it to O(vlogv)

    • profile image

      Ankit 

      6 years ago

      The concept of parent array(p) is very nice but the running time I think is quite high O(V^3 + E) because you

      are searching for the minimum again and again.Instead you sort them once which will require O(VlgV) time.

    • profile image

      carnoot 

      6 years ago

      Nice tutorial, however there are some errors at the end of the kruskal method. With the printing stuff. Stratos is right, though.

    • profile image

      subbu 

      7 years ago

      youer gaidence very useful thanks for me

    • profile image

      FUCK MASTER'S 

      7 years ago

      lelo ji lelo ......

    • profile image

      Stratos 

      7 years ago

      There is an error at the code. The line

      while(count < n)

      should be:

      while (count < num_of_Edges)

    • prabhakar gouda profile imageAUTHOR

      prabhakar gouda 

      7 years ago from Bangalore

      hey good observation ..... but has to be declared as t[100][2] right

    • profile image

      Janus 

      7 years ago

      Thanks for your wonderful code.

      However, why did you have this t[100][100],instead of t[100][1].

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)