You are on page 1of 23

DAA MINI PROJECT

NAME:T.MITHILESHWAR REDDY
SECTION: F1
REG.NO: RA2111003010362
TEAMMATE: A.N.CHARITESH
Kruskal’s algorithm:
Given a connected and undirected graph, a spanning tree of that graph is a
subgraph that is a tree and connects all the vertices together. A single
graph can have many different spanning trees. A minimum spanning tree
(MST) or minimum weight spanning tree for a weighted, connected and
undirected graph is a spanning tree with weight less than or equal to the
weight of every other spanning tree. The weight of a spanning tree is the
sum of weights given to each edge of the spanning tree.
Below are the steps for finding MST using Kruskal’s 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 the cycle is not formed, include this edge.
Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

Pseudocode for Kruskal: –

// Cost – 2 dimensional matrix, cost[u][v] is cost of edge (u,v);

// n no. of vertices.

//‘t’ set of edges in minimum spanning tree – it us a 2D array. t[1…..n][1….2]

// initially each vertex is in different set.


1. Construct a minimum heap out of edge costs using heapify.
2. For( i = 1 to n) do parent[i] = -1;

// each vertex is in different set.I=0; mincost=0;

3. While(i

)>{

4. Delete minimum cost edge (u,v) from heap


5. Reheapify using adjust.
6. J=find(u); k=find(v);
7. If (j!=k) then\
8. {
9. I++; t[i][1]=u,t[i][2]=v;
10. Union(j,k); mincost = mincost+cost[u][v];
11. }
12. }

Algorithm:
SimpleUnion (I, j) // i & j are roots of sets.

p[i] = j;

Algorithm SimpleFind (i ) // return root of ‘i’

while (p[i] >=0) do i=p[i];

return I;

}
If we want to perform n-1 unions then can be processed in Linear time O(n)

The time required to process a find for an element at level ‘i’ of a tree is O(i), so total time
needed to process n finds is O(n^2)

One can improve the performance of our union & find by avoiding creation of
degenerating trees.

We apply weighting rule for Union, which says that if the number of nodes in the tree with
root i is less than the number of nodes in the tree with root j, then make j as the parent of i,
otherwise make i, as the parent of j. Thus we avoid degenerated/skewed trees.

Similarly we use CollapseFind , to improve the performance of find. In CollapsingFind, we


are required to go up to reach the root node and then reset the links. Every first find has to
go through intermediate nodes to go up to root node, but every next find on similar node
will require only one link to go up, thus reducing the cost cost of find. Collapsing rule says
that, if j is a node on the path from i to its root node and p[i] is not root[i], then set p[j] to
root[i].Weighted union(I,j)

Temp=p[i]+p[j];

If(p[i]>p[j]) // i has fewer nodes

p[i]=j, p[j]=temp;

Else

p[j]=I; // j has fewer nodes

p[i]=temp;
}

Collapse Find(i)

r=I;

While(p[r]>=0)

r=p[r];

while(i=r)

s=p[i];

p[i]=r;

i=s;

EXAMPLE:

Input Graph:
The graph contains 9 vertices and 14 edges. So, the minimum spanning tree
formed will be having (9 – 1) = 8 edges.
After sorting:

Weight Source Destination

1 7 6

2 8 2

2 6 5

4 0 1

4 2 5

6 8 6

7 2 3

7 7 8

8 0 7

8 1 2

9 3 4

10 5 4

11 1 7

14 3 5

Now pick all edges one by one from the sorted list of edges
Step 1: Pick edge 7-6. No cycle is formed, include it.
Add edge 7-6 in the MST

Step 2: Pick edge 8-2. No cycle is formed, include it.

Add edge 8-2 in the MST

Step 3: Pick edge 6-5. No cycle is formed, include it.

Add edge 6-5 in the MST

Step 4: Pick edge 0-1. No cycle is formed, include it.


Add edge 0-1 in the MST

Step 5: Pick edge 2-5. No cycle is formed, include it.

Add edge 2-5 in the MST

Step 6: Pick edge 8-6. Since including this edge results in the cycle, discard it. Pick
edge 2-3: No cycle is formed, include it.

Add edge 2-3 in the MST

Step 7: Pick edge 7-8. Since including this edge results in the cycle, discard it. Pick
edge 0-7. No cycle is formed, include it.
Add edge 0-7 in MST

Step 8: Pick edge 1-2. Since including this edge results in the cycle, discard it. Pick
edge 3-4. No cycle is formed, include it.

Add edge 3-4 in the

SOURCE CODE:

#include <stdio.h>

#include <stdlib.h>

// Comparator function to use in sorting

int comparator(const void* p1, const void* p2)

const int(*x)[3] = p1;

const int(*y)[3] = p2;


return (*x)[2] - (*y)[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

void 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;

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 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;

printf("%d -- %d == %d\n", edge[i][0],

edge[i][1], wt);

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

// Driver code

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;

OUTPUT:
Following are the edges in the constructed MST:

2 – 3 == 4
0 – 3 == 5
0 – 1 == 10
Minimum cost spanning tree : 19-- 1 == 10

Time Complexity: O(E * logE) or O(E * logV)


 Sorting of edges takes O(E * logE) time.
 After sorting, we iterate through all edges and apply the find-union
algorithm. The find and union operations can take at most O(logV) time.
 So overall complexity is O(E * logE + E * logV) time.
 The value of E can be at most O(V2), so O(logV) and O(logE) are the
same. Therefore, the overall time complexity is O(E * logE) or O(E*logV)

Auxiliary Space: O(V + E), where V is the number of vertices and E is


the number of edges in the graph.
PRIM’S ALGORITHM:
Like Kruskal’s algorithm, Prim’s algorithm is also a Greedy algorithm. It starts with
an empty spanning tree. The idea is to maintain two sets of vertices. The first set
contains the vertices already included in the MST, the other set contains the
vertices not yet included. At every step, it considers all the edges that connect the
two sets and picks the minimum weight edge from these edges. After picking the
edge, it moves the other endpoint of the edge to the set containing MST.
Below are the steps for finding MST using Prim’s algorithm
1. Create a set mstSet that keeps track of vertices already included in MST.
2. Assign a key value to all vertices in the input graph. Initialize all key
values as INFINITE. Assign key value as 0 for the first vertex so that it is
picked first.
3. While mstSet doesn’t include all vertices
 Pick a vertex u which is not there in mstSet and has minimum
key value.
 Include u to mstSet.
 Update the key value of all adjacent vertices of u. To update
the key values, iterate through all adjacent vertices. For every
adjacent vertex v, if the weight of edge u-v is less than the
previous key value of v, update the key value as the weight of
u-v
PSEUDOCODE:
prim(graph):
# Initialize an empty set to hold the vertices in the minimum spanning tree
mst = empty set

# Select the first vertex to start the tree


startVertex = first vertex in graph
mst.add(startVertex)

# Initialize the set of edges to consider


edges = edges connected to startVertex

# Iterate until all vertices are in the minimum spanning tree


while mst has fewer vertices than graph:
# Find the minimum edge in the set of edges
minEdge, minWeight = findMinEdge(edges)
# Add the vertex to the minimum spanning tree
mst.add(minEdge)

# Add the edges connected to the vertex to the set of edges to consider
for edge in edges connected to minEdge:
if edge is not in mst:
edges.add(edge)

# Remove the minimum edge from the set of edges to consider


edges.remove(minEdge)

# Return the minimum spanning tree as an array


return mst as an array

ALGORITHM:
1. Step 1: Select a starting vertex
2. Step 2: Repeat Steps 3 and 4 until there are fringe vertices
3. Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has
minimum weight
4. Step 4: Add the selected edge and the vertex to the minimum spanning tree T

5. [END OF LOOP]
6. Step 5: EXIT

EXAMPLE:
Consider the following graph as an example for which we need to finnning

Tree (MST). Example of a graph

Step 1: Firstly,
we select an arbitrary
vertex that acts as the
starting vertex of
the Minimum
Sp

0 is selected as starting vertex

Step 2: All the edges connecting the incomplete MST and other vertices are
the edges {0, 1} and {0, 7}. Between these two the edge with minimum
weight is {0, 1}. So include the edge and vertex 1 in the MST.

1 is added to the MST


Step 3: The edges connecting the incomplete MST to other vertices are {0,
7}, {1, 7} and {1, 2}. Among these edges the mi

nimum weig ht is 8ges that


connect the incomplete MST with the fringe vertices are {1, 2}, {7, 6} and {7,
8}. Add the edge {7, 6} and the vertex 6 in the MST as it has the least
weight (i.e., 1).

6 is added in the MST

Step 5: The connecting edges now are {7, 8}, {1, 2}, {6, 8} and {6, 5}. Include
edge {6, 5} and vertex 5 in the MST as the edge has the minimum weight
(i.e., 2) among them.
Include vertex 5 in the MST

Step 6: Among the current connecting edges, the edge {5, 2} has the
minimum weight. So include that edge and the vertex 2 in the MST.

Include vertex 2 in the MST

Step 7: The connecting edges between the incomplete MST and the other
edges are {2, 8}, {2, 3}, {5, 3} and {5, 4}. The edge with minimum weight is
edge {2, 8} which has weight 2. So include this edge and the vertex 8 in the
MST.

Add vertex 8 in the MST


Step 8: See here that the edges {7, 8} and {2, 3} both have same weight
which are minimum. But 7 is already part of MST. So we will consider the
edge {2, 3} and include that edge and vertex 3 in the MST.

Include vertex 3 in MST

Step 9: Only the vertex 4 remains to be included. The minimum weighted


edge from the incomplete MST to 4 is {3, 4}.

Include vertex 4 in the MST

The final structure of the MST is as follows and the weight of the edges of
the MST is (4 + 8 + 1 + 2 + 4 + 2 + 7 + 9) = 37.
The structure of the MST formed using the above method

Note: If we had selected the edge {1, 2} in the third step then the MST
would look like the following.

Structure of the alternate MST if we had selected edge {1, 2} in the MST

SOURCE CODE:
#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[i][parent[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 } };

primMST(graph);
return 0;
}

OUTPUT:
EDGE WEIGHT
0 – 1 2
1 – 2 3
0 - 3 6
1 – 4 5
1EdEDge Weight

Time Complexity: O(V ), If the input graph is represented using an


2

adjacency list, then the time complexity of Prim’s algorithm can be reduced
to O(E * logV) with the help of a binary heap. In this implementation, we
are always considering the spanning tree to start from the root of the graph
Auxiliary Space: O(V)0 - 1 2

1 - 2 3
0

Advantages:
1. Prim’s algorithm is guaranteed to find the MST in a connected,
weighted graph.
2. It has a time complexity of O(E log V) using a binary heap or
Fibonacci heap, where E is the number of edges and V is the
number of vertices.
3. It is a relatively simple algorithm to understand and implement
compared to some other MST algorithms.

Disadvantages:
1. Like Kruskal’s algorithm, Prim’s algorithm can be slow on dense
graphs with many edges, as it requires iterating over all edges at
least once.
2. Prim’s algorithm relies on a priority queue, which can take up extra
memory and slow down the algorithm on very large graphs.
3. The choice of starting node can affect the MST output, which may
not be desirable in some applications.
REAL TIME APPLICATIONS OF PRIM’S AND KRUSKAL’S
ALGORITHM:
Prim’s and kruskal’s algorithms have many use cases they are used in solving traveling
salesman problems, LAN networks, TV networks, and in general for any network where we
need to find the least cost subset of this network such that any two nodes are connected.

THE END

You might also like