0% found this document useful (0 votes)
20 views8 pages

Algorithms Lab Ex 5

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

Department of

Computer Science and Engineering

Title: Implement Kruskal’s Algorithm

Algorithms Lab
CSE 206

Green University of Bangladesh


1 Objective(s)
• To learn Kruskal’s algorithm to find Minimum Spanning Tree (MST) of a graph.

2 Problem Analysis
2.1 Kruskal’s Algorithm
Kruskal’s algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the subset of
the edges of that graph which
• form a tree that includes every vertex.
• has the minimum sum of weights among all the trees that can be formed from the graph.

2.2 How Kruskal’s algorithm works


It falls under a class of algorithms called greedy algorithms that find the local optimum in the hopes of finding
a global optimum. We start from the edges with the lowest weight and keep adding edges until we reach our
goal. The steps for implementing Kruskal’s algorithm are as follows:

• Sort all the edges from low weight to high.

• Take the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle,
then reject this edge.
• Keep adding edges until we reach all vertices.

2.3 Kruskal’s Algorithm Complexity


The time complexity Of Kruskal’s Algorithm is: O(E log E).

2.4 Example of Kruskal’s algorithm

Figure 1: Start with a weighted graph


(a) Choose the edge with the least weight, if there are more
(b) Choose the next shortest edge and add it
than 1, choose anyone

Figure 2: Step 2 and 3

(a) Choose the next shortest edge that doesn’t create a cycle (b) Choose the next shortest edge that doesn’t create a cycle
and add it and add it

Figure 3: Step 4 and 5

Figure 4: Repeat until you have a spanning tree


3 Algorithm
Algorithm 1: Kruskal Algorithm

1 KRUSKAL(G):
2 A=∅
3 for each vertex v ∈ G.V: do
4 MAKE-SET(v)
5 end
6 for each edge (u, v) ∈ G.E ordered by increasing order by weight(u, v): do
7 if FIND-SET(u) 6= FIND-SET(v): then
8 A = A ∪ (u, v)
9 UNION(u, v)
10 end
11 end
12 return A

4 Implementation in Java
1 // Java program for Kruskal’s algorithm to
2 // find Minimum Spanning Tree of a given
3 //connected, undirected and weighted graph
4 import java.util.*;
5 import java.lang.*;
6 import java.io.*;
7
8 class Graph {
9 // A class to represent a graph edge
10 class Edge implements Comparable<Edge>
11 {
12 int src, dest, weight;
13
14 // Comparator function used for
15 // sorting edgesbased on their weight
16 public int compareTo(Edge compareEdge)
17 {
18 return this.weight − compareEdge.weight;
19 }
20 };
21
22 // A class to represent a subset for
23 // union−find
24 class subset
25 {
26 int parent, rank;
27 };
28
29 int V, E; // V−> no. of vertices & E−>no.of edges
30 Edge edge[]; // collection of all edges
31
32 // Creates a graph with V vertices and E edges
33 Graph(int v, int e)
34 {
35 V = v;
36 E = e;
37 edge = new Edge[E];
38 for (int i = 0; i < e; ++i)
39 edge[i] = new Edge();
40 }
41
42 // A utility function to find set of an
43 // element i (uses path compression technique)
44 int find(subset subsets[], int i)
45 {
46 // find root and make root as parent of i
47 // (path compression)
48 if (subsets[i].parent != i)
49 subsets[i].parent
50 = find(subsets, subsets[i].parent);
51
52 return subsets[i].parent;
53 }
54
55 // A function that does union of two sets
56 // of x and y (uses union by rank)
57 void Union(subset subsets[], int x, int y)
58 {
59 int xroot = find(subsets, x);
60 int yroot = find(subsets, y);
61
62 // Attach smaller rank tree under root
63 // of high rank tree (Union by Rank)
64 if (subsets[xroot].rank
65 < subsets[yroot].rank)
66 subsets[xroot].parent = yroot;
67 else if (subsets[xroot].rank
68 > subsets[yroot].rank)
69 subsets[yroot].parent = xroot;
70
71 // If ranks are same, then make one as
72 // root and increment its rank by one
73 else {
74 subsets[yroot].parent = xroot;
75 subsets[xroot].rank++;
76 }
77 }
78
79 // The main function to construct MST using Kruskal’s
80 // algorithm
81 void KruskalMST()
82 {
83 // Tnis will store the resultant MST
84 Edge result[] = new Edge[V];
85
86 // An index variable, used for result[]
87 int e = 0;
88
89 // An index variable, used for sorted edges
90 int i = 0;
91 for (i = 0; i < V; ++i)
92 result[i] = new Edge();
93
94 // Step 1: Sort all the edges in non−decreasing
95 // order of their weight. If we are not allowed to
96 // change the given graph, we can create a copy of
97 // array of edges
98 Arrays.sort(edge);
99
100 // Allocate memory for creating V ssubsets
101 subset subsets[] = new subset[V];
102 for (i = 0; i < V; ++i)
103 subsets[i] = new subset();
104
105 // Create V subsets with single elements
106 for (int v = 0; v < V; ++v)
107 {
108 subsets[v].parent = v;
109 subsets[v].rank = 0;
110 }
111
112 i = 0; // Index used to pick next edge
113
114 // Number of edges to be taken is equal to V−1
115 while (e < V − 1)
116 {
117 // Step 2: Pick the smallest edge. And increment
118 // the index for next iteration
119 Edge next_edge = edge[i++];
120
121 int x = find(subsets, next_edge.src);
122 int y = find(subsets, next_edge.dest);
123
124 // If including this edge does’t cause cycle,
125 // include it in result and increment the index
126 // of result for next edge
127 if (x != y) {
128 result[e++] = next_edge;
129 Union(subsets, x, y);
130 }
131 // Else discard the next_edge
132 }
133
134 // print the contents of result[] to display
135 // the built MST
136 System.out.println("Following are the edges in "
137 + "the constructed MST");
138 int minimumCost = 0;
139 for (i = 0; i < e; ++i)
140 {
141 System.out.println(result[i].src + " −− "
142 + result[i].dest
143 + " == " + result[i].weight);
144 minimumCost += result[i].weight;
145 }
146 System.out.println("Minimum Cost Spanning Tree "
147 + minimumCost);
148 }
149
150 // Driver Code
151 public static void main(String[] args)
152 {
153
154 /* Let us create following weighted graph
155 10
156 0−−−−−−−−1
157 | \ |
158 6| 5\ |15
159 | \ |
160 2−−−−−−−−3
161 4 */
162 int V = 4; // Number of vertices in graph
163 int E = 5; // Number of edges in graph
164 Graph graph = new Graph(V, E);
165
166 // add edge 0−1
167 graph.edge[0].src = 0;
168 graph.edge[0].dest = 1;
169 graph.edge[0].weight = 10;
170
171 // add edge 0−2
172 graph.edge[1].src = 0;
173 graph.edge[1].dest = 2;
174 graph.edge[1].weight = 6;
175
176 // add edge 0−3
177 graph.edge[2].src = 0;
178 graph.edge[2].dest = 3;
179 graph.edge[2].weight = 5;
180
181 // add edge 1−3
182 graph.edge[3].src = 1;
183 graph.edge[3].dest = 3;
184 graph.edge[3].weight = 15;
185
186 // add edge 2−3
187 graph.edge[4].src = 2;
188 graph.edge[4].dest = 3;
189 graph.edge[4].weight = 4;
190
191 // Function call
192 graph.KruskalMST();
193 }
194 }

5 Sample Input/Output (Compilation, Debugging & Testing)


Following are the edges in the constructed MST

2 – 3 == 4
0 – 3 == 5
0 – 1 == 10

Minimum Cost Spanning Tree: 19

6 Discussion & Conclusion


Based on the focused objective(s) to understand about the MST algorithms, the additional lab exercise made
me more confident towards the fulfilment of the objectives(s).
7 Lab Task (Please implement yourself and show the output to the
instructor)
1. Write a Program in java to find the Second Best Minimum Spanning Tree using Kruskal Algorithm.

7.1 Problem analysis


A Minimum Spanning Tree T is a tree for the given graph G which spans over all vertices of the given graph
and has the minimum weight sum of all the edges, from all the possible spanning trees. A second best MST T0
is a spanning tree, that has the second minimum weight sum of all the edges, from all the possible spanning
trees of the graph G.

7.2 Using Kruskal’s Algorithm


We can use Kruskal’s algorithm to find the MST first, and then just try to remove a single edge from it and
replace it with another.
1. Sort the edges in O(ElogE), then find a MST using Kruskal in O(E).

2. For each edge in the MST (we will have V−1 edges in it) temporarily exclude it from the edge list so that
it cannot be chosen.
3. Then, again try to find a MST in O(E) using the remaining edges.
4. Do this for all the edges in MST, and take the best of all.
Note: we don’t need to sort the edges again in for Step 3.

(a) MST (b) Second Best MST

Figure 5: In this figure left is the MST and right is the second best MST

8 Lab Exercise (Submit as a report)


• Find the number of distinct minimum spanning trees for a given weighted graph.

9 Policy
Copying from internet, classmate, seniors, or from any other source is strongly prohibited. 100% marks will be
deducted if any such copying is detected.

You might also like