9117lab Manual Expt No. 5 AOA - MST Using Greedy Method
9117lab Manual Expt No. 5 AOA - MST Using Greedy Method
Experiment No.05
A.1 Aim:
Write a program to implement minimum cost spanning trees using Greedy Method
Approach – Kruskal Algorithm and Prim’s Algorithm.
A.2 Prerequisite:
A.3 Outcome:
After successful completion of this experiment, students will be able to apply greedy
method approach to different problems to find optimal solution and analyze the
complexity of the problem.
A.4 Theory:
Kruskal's algorithm :
Algorithm:
Time Complexity:
Time complexity is large as order of O(V+E) where V is the number of vertices, E is the
number of edges.
Prim’s algorithm:
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for
a weighted undirected 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. The algorithm operates by building this tree one vertex at a time, from an
arbitrary starting vertex, at each step adding the cheapest possible connection from the
tree to another vertex.
Algorithm:
1. Maintain two disjoint sets of vertices. One containing vertices that are in the growing
spanning tree and other that are not in the growing spanning tree.
2. Select the cheapest vertex that is connected to the growing spanning tree and is not
in the growing spanning tree and add it into the growing spanning tree. This can be
done using Priority Queues. Insert the vertices, that are connected to growing
spanning tree, into the Priority Queue.
3. Check for cycles. To do that, mark the nodes which have been already selected and
insert only those nodes in the Priority Queue that are not marked.
Example:
Time Complexity:
The time complexity of the Prim’s Algorithm is O((V+E)logV) because each vertex is
inserted in the priority queue only once and insertion in priority queue take logarithmic
time.
PART B
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Edge {
int src, dest, weight;
};
struct Graph {
int V, E;
struct Edge* edges;
};
int main() {
struct Graph* graph = (struct
Graph*)malloc(sizeof(struct Graph));
graph->V = 4; // Number of vertices
graph->E = 5; // Number of edges
printf("Kruskal's Algorithm:\n");
kruskalMST(graph);
printf("\nPrim's Algorithm:\n");
primMST(graph);
free(graph->edges);
free(graph);
return 0;
}
if (x != y) {
result[e++] = next_edge;
Union(parent, x, y);
}
}
key[0] = 0;
parent[0] = -1;
mstSet[u] = true;