Prims Kruskals RK
Prims Kruskals RK
1. Prim’s Algorithm:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
//Raghav Kohli – 23BCI0219
#define vertices 8
addEdge(graph, 1, 2, 28);
addEdge(graph, 1, 6, 10);
addEdge(graph, 2, 3, 16);
addEdge(graph, 2, 7, 14);
addEdge(graph, 3, 4, 12);
addEdge(graph, 4, 5, 22);
addEdge(graph, 4, 7, 18);
addEdge(graph, 5, 6, 25);
addEdge(graph, 5, 7, 24);
primMST(graph);
}
Output:
2. Kruskal’s Algorithm:
#define vertices 8
#define edges 9
typedef struct
{
int u, v, weight;
} Edge;
Edge graph[edges];
int edgeCount = 0;
int parent[vertices];
int find(int i)
{
if (parent[i] == i)
return i;
return parent[i] = find(parent[i]);
}
void kruskalMST()
{
// sorting in ascending order- the edge wts.
qsort(graph, edgeCount, sizeof(Edge), compare);
//checking cyclicity
if (find(u) != find(v)) {
printf("%d - %d %d\n", u, v, weight);
mstwt += weight;
unionSets(u, v);
}
}
kruskalMST();
}
Ouput:
So, we have successfully applied Prim’s and Kruskal’s Algo to the given graph manually, and verified our results
through code in C.