Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Krushkal MST in C #355

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions krukal_MST_in_C.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@


#include <stdio.h>
#include <stdlib.h>


int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;

return (*x)[2] - (*y)[2];
}


void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}


int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;

return parent[component]
= findParent(parent, parent[component]);
}


void unionSet(int u, int v, int parent[], int rank[], int n)
{

u = findParent(parent, u);
v = findParent(parent, v);

if (rank[u] < rank[v]) {
parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u;


rank[u]++;
}
}


void kruskalAlgo(int n, int edge[n][3])
{

qsort(edge, n, sizeof(edge[0]), comparator);

int parent[n];
int rank[n];


makeSet(parent, rank, n);


int minCost = 0;

printf(
"Following are the edges in the constructed MST\n");
for (int i = 0; i < n; i++) {
int v1 = findParent(parent, edge[i][0]);
int v2 = findParent(parent, edge[i][1]);
int wt = edge[i][2];


if (v1 != v2) {
unionSet(v1, v2, parent, rank, n);
minCost += wt;
printf("%d -- %d == %d\n", edge[i][0],
edge[i][1], wt);
}
}

printf("Minimum Cost Spanning Tree: %d\n", minCost);
}


int main()
{
int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };

kruskalAlgo(5, edge);

return 0;
}
Binary file added krukal_MST_in_C.exe
Binary file not shown.