0% found this document useful (0 votes)
9 views18 pages

AOA Exp 5 b44

The document outlines an experiment focused on implementing minimum cost spanning trees using Kruskal's and Prim's algorithms. It includes theoretical explanations, algorithms, and C code implementations for both algorithms, along with observations, learning outcomes, and applications of minimum spanning trees. The document concludes with questions regarding the properties and implications of minimum spanning trees.

Uploaded by

shettysiya09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

AOA Exp 5 b44

The document outlines an experiment focused on implementing minimum cost spanning trees using Kruskal's and Prim's algorithms. It includes theoretical explanations, algorithms, and C code implementations for both algorithms, along with observations, learning outcomes, and applications of minimum spanning trees. The document concludes with questions regarding the properties and implications of minimum spanning trees.

Uploaded by

shettysiya09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PART A

(PART A: TO BE REFFERED BY STUDENTS)

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 :

Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the


least possible weight that connects any two trees in the forest. It is a greedy algorithm in
graph theory as it finds a minimum spanning tree for a connected graph adding increasing
cost arcs at each step. 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.

Algorithm:

1. Sort all the edges in non-decreasing order of their weight.


2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far.
If cycle is not formed, include this edge. Else, discard it.
3. Repeat step 2 until there are (V-1) edges in the spanning tree.
Example:

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
(PART B : TO BE COMPLETED BY STUDENTS)

Roll No.: B044 Name: Siya Shetty


Class: SE-B Batch: B2
Date of Experiment: 04-03-2025 Date of Submission 04-03-2025
Grade:

B.1 Software Code written by student:

Kruskal’s Algorithm:
// C code to implement Kruskal's algorithm

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

// Comparator function to use in sorting


int comparator(const int p1[], const int p2[])
{
return p1[2] - p2[2];
}

// Initialization of parent[] and rank[] arrays


void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
// Function to find the parent of a node
int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;

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

// Function to unite two sets


void unionSet(int u, int v, int parent[], int rank[], int n)
{
// Finding the parents
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;

// Since the rank increases if


// the ranks of two sets are same
rank[u]++;
}
}

// Function to find the MST


int kruskalAlgo(int n, int edge[n][3])
{
// First we sort the edge array in ascending order
// so that we can access minimum distances/cost
qsort(edge, n, sizeof(edge[0]), comparator);

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

// Function to initialize parent[] and rank[]


makeSet(parent, rank, n);
// To store the minimun cost
int minCost = 0;
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 the parents are different that


// means they are in different sets so
// union them
if (v1 != v2) {
unionSet(v1, v2, parent, rank, n);
minCost += wt;
}
}

return minCost;
}

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

printf("%d",kruskalAlgo(5, edge));

return 0;
}

Prims’s Algorithm:
// A C program for Prim's Minimum
// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 5

// A utility function to find the vertex with


// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

// A utility function to print the


// constructed MST stored in parent[]
int printMST(int parent[], int graph[V][V])
{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i,
graph[parent[i]][i]);
}

// Function to construct and print MST for


// a graph represented using adjacency
// matrix representation
void primMST(int graph[V][V])
{
// Array to store constructed MST
int parent[V];
// Key values used to pick minimum weight edge in cut
int key[V];
// To represent set of vertices included in MST
bool mstSet[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
// Always include first 1st vertex in MST.
// Make key 0 so that this vertex is picked as first
// vertex.
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the


// set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of


// the adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent


// vertices of m mstSet[v] is false for vertices
// not yet included in MST Update the key only
// if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false
&& graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// print the constructed MST


printMST(parent, graph);
}

// Driver's code
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


primMST(graph);

return 0;
}
B.2 Input and Output:

Kruskal’s Algorithm:
Output:
Prim’s Algorithm:
Output:
B.3 Observations and learning:

Observation:
Kruskal’s Algorithm selects edges in increasing weight order, while Prim’s Algorithm grows the
MST from a starting node. Both efficiently find the Minimum Spanning Tree.

Learning:
We learned how Greedy Methods optimize network connections by minimizing costs while
maintaining full connectivity.

B.4 Conclusion:

Kruskal’s and Prim’s Algorithms effectively construct a Minimum Spanning Tree using the Greedy
approach. Kruskal’s works well with edge lists, while Prim’s is efficient for dense graphs, ensuring
minimal cost connectivity in networks and optimization problems.

B.5 Question of Curiosity

Q1: What are the applications of Minimum Spanning Tree?

Minimum Spanning Tree (MST) has various applications in computer science, networking, and
optimization. Some key applications include:

1. Network Design: Used in designing network infrastructures like computer networks,


telecommunication networks, and electrical grids with minimal cost.

2. Clustering: Helps in hierarchical clustering by connecting similar data points with minimal
distance.

3. Approximation Algorithms: Used in algorithms like the Traveling Salesman Problem (TSP) to find
near-optimal solutions.

4. Image Segmentation: Helps in partitioning images into meaningful regions by minimizing edge
weights.

5. Routing and Broadcasting: Used in network routing protocols like OSPF (Open Shortest Path
First) to minimize data transfer costs.

6. Circuit Design: Helps in designing efficient VLSI circuits by minimizing wire length.
7. Transportation and Logistics: Used in planning roads, pipelines, and distribution networks to
reduce infrastructure costs.

MST is a fundamental concept in graph theory with numerous real-world applications requiring
cost-effective connectivity.

Q2: How many edges do a minimum spanning tree has?

A Minimum Spanning Tree (MST) of a connected graph with NN vertices always has N−1N-1 edges.

This is because:

 An MST is a tree, meaning it connects all vertices without cycles.

 A tree with NN vertices always has N−1N-1 edges, ensuring connectivity while minimizing cost.

Q3: Consider an undirected graph G with unique positive weights. Suppose it has
a minimum spanning tree T. If we square all the edge weights and compute
the MST again, do we still get the same tree structure? Explain briefly.

No, the Minimum Spanning Tree (MST) may change if we square all edge
weights.

Explanation:

1. MST Selection Criteria:

o MST algorithms like Kruskal’s or Prim’s select edges based on the relative
order of weights (i.e., comparing edge weights).

o If edge weights are unique and positive, the original MST T is determined
based on the order of weights.

2. Effect of Squaring Weights:


o Squaring a function f(w)=w2f(w) = w^2 is monotonic (i.e., it preserves
order), meaning if w1<w2w_1 < w_2, then w12<w22w_1^2 < w_2^2.

o However, the relative differences between weights change, which can


affect the MST structure.

3. Example Where MST Changes:

o Suppose the original graph has edge weights 2,3,52, 3, 5.

o The squared weights become 4,9,254, 9, 25.

o The difference between **33 and 55 was 22, but after squaring, it becomes
1616, which might change the order of MST edge selection.

Conclusion:

Although the order of edge weights is preserved, the differences between them
change, which can lead to a different MST structure when the algorithm
recomputes it. Thus, squaring edge weights can change the MST.

************************

You might also like