{"id":24968,"date":"2017-05-27T18:13:04","date_gmt":"2017-05-27T12:43:04","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=24968"},"modified":"2017-05-27T18:24:30","modified_gmt":"2017-05-27T12:54:30","slug":"kruskals-minimum-spanning-tree-algorithm","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/kruskals-minimum-spanning-tree-algorithm\/","title":{"rendered":"Kruskal\u2019s Minimum Spanning Tree Algorithm"},"content":{"rendered":"<p>What is Kruskals Minimum Spanning Tree Algorithm?<\/p>\n<p>Given a connected and undirected graph, a <a href=\"https:\/\/www.wikitechy.com\/technology\/amortized-analysis-introduction\/\">spanning tree<\/a> of that graph is a subgraph that is a tree and connects all the vertices together. <span id=\"more-26604\"><\/span>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.<\/p>\n<p>How many edges does a minimum spanning tree has?<\/p>\n<p>A minimum spanning tree has (V \u2013 1) edges where V is the number of vertices in the given graph.<\/p>\n<p>What are the applications of Minimum Spanning Tree?<\/p>\n<p>See this for applications of MST.<\/p>\n<p><strong>Below are the steps for finding MST using Kruskal\u2019s algorithm<\/strong><\/p>\n<pre>Sort all the edges in non-decreasing order of their weight.\r\n\r\nPick the smallest edge. Check if it forms a cycle with the spanning tree \r\nformed so far. If cycle is not formed, include this edge. Else, discard it.  \r\n\r\nRepeat step#2 until there are (V-1) edges in the spanning tree.<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p>The step#2 uses Union-Find algorithm to detect cycle. So we recommend to read following post as a prerequisite.<\/p>\n<p>Union-Find Algorithm | Set 1 (Detect Cycle in a Graph)<\/p>\n<p>Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)<\/p>\n<p>The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight edge that does not cause a cycle in the MST constructed so far. Let us understand it with an example: Consider the below input graph.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-24996\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-8.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"139\" \/><\/p>\n<p>The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be having (9 \u2013 1) = 8 edges.<\/p>\n<pre>After sorting:\r\nWeight   Src    Dest\r\n1         7      6\r\n2         8      2\r\n2         6      5\r\n4         0      1\r\n4         2      5\r\n6         8      6\r\n7         2      3\r\n7         7      8\r\n8         0      7\r\n8         1      2\r\n9         3      4\r\n10        5      4\r\n11        1      7\r\n14        3      5<\/pre>\n<p>Now pick all edges one by one from sorted list of edges<\/p>\n<p><strong>1.<\/strong> Pick edge 7-6: No cycle is formed, include it.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-24989\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-1.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"264\" height=\"72\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-1.png 264w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-1-260x72.png 260w\" sizes=\"(max-width: 264px) 100vw, 264px\" \/><\/p>\n<p><strong>2.<\/strong> Pick edge 8-2: No cycle is formed, include it.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-24990\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-2.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"264\" height=\"328\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-2.png 264w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-2-241x300.png 241w\" sizes=\"(max-width: 264px) 100vw, 264px\" \/><\/p>\n<p><strong>3. Pick edge 6-5: No cycle is formed, include it.<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-24991\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-3.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"232\" \/><\/p>\n<p><strong>4.<\/strong> Pick edge 0-1: No cycle is formed, include it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-24992\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-4.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"175\" \/><\/p>\n<p><strong>5.<\/strong> Pick edge 2-5: No cycle is formed, include it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-24993\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-5.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"175\" \/><\/p>\n<p><strong>6.<\/strong> Pick edge 8-6: Since including this edge results in cycle, discard it.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>7.<\/strong> Pick edge 2-3: No cycle is formed, include it.<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-24994\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-6.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"175\" \/><\/p>\n<p><strong>8.<\/strong> Pick edge 7-8: Since including this edge results in cycle, discard it.<\/p>\n<p><strong>9.<\/strong> Pick edge 0-7: No cycle is formed, include it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-24995\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-7.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"175\" \/><\/p>\n<p><strong>10.<\/strong> Pick edge 1-2: Since including this edge results in cycle, discard it.<\/p>\n<p><strong>11.<\/strong> Pick edge 3-4: No cycle is formed, include it.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-24996\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/kruskals-minimum-spanning-8.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree Algorithm\" width=\"300\" height=\"139\" \/><\/p>\n<p>Since the number of edges included equals (V \u2013 1), the algorithm stops here.<\/p>\n<div id=\"practice\">\n<h4 id=\"recommended\">Recommended:<\/h4>\n<h4 id=\"please-try-your-approach-on-ide-first-before-moving-on-to-the-solution\">Please try your approach on <b><u>{IDE}<\/u><\/b> first, before moving on to the solution.<\/h4>\n<h4 id=\"c\"><strong>C++<\/strong><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program for Kruskal&#039;s algorithm to find Minimum Spanning Tree<br\/>\/\/ of a given connected, undirected and weighted graph<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/>#include &lt;string.h&gt;<br\/> <br\/>\/\/ a structure to represent a weighted edge in graph<br\/>struct Edge<br\/>{<br\/>    int src, dest, weight;<br\/>};<br\/> <br\/>\/\/ a structure to represent a connected, undirected and weighted graph<br\/>struct Graph<br\/>{<br\/>    \/\/ V-&gt; Number of vertices, E-&gt; Number of edges<br\/>    int V, E;<br\/> <br\/>    \/\/ graph is represented as an array of edges. Since the graph is<br\/>    \/\/ undirected, the edge from src to dest is also edge from dest<br\/>    \/\/ to src. Both are counted as 1 edge here.<br\/>    struct Edge* edge;<br\/>};<br\/> <br\/>\/\/ Creates a graph with V vertices and E edges<br\/>struct Graph* createGraph(int V, int E)<br\/>{<br\/>    struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );<br\/>    graph-&gt;V = V;<br\/>    graph-&gt;E = E;<br\/> <br\/>    graph-&gt;edge = (struct Edge*) malloc( graph-&gt;E * sizeof( struct Edge ) );<br\/> <br\/>    return graph;<br\/>}<br\/> <br\/>\/\/ A structure to represent a subset for union-find<br\/>struct subset<br\/>{<br\/>    int parent;<br\/>    int rank;<br\/>};<br\/> <br\/>\/\/ A utility function to find set of an element i<br\/>\/\/ (uses path compression technique)<br\/>int find(struct subset subsets[], int i)<br\/>{<br\/>    \/\/ find root and make root as parent of i (path compression)<br\/>    if (subsets[i].parent != i)<br\/>        subsets[i].parent = find(subsets, subsets[i].parent);<br\/> <br\/>    return subsets[i].parent;<br\/>}<br\/> <br\/>\/\/ A function that does union of two sets of x and y<br\/>\/\/ (uses union by rank)<br\/>void Union(struct subset subsets[], int x, int y)<br\/>{<br\/>    int xroot = find(subsets, x);<br\/>    int yroot = find(subsets, y);<br\/> <br\/>    \/\/ Attach smaller rank tree under root of high rank tree<br\/>    \/\/ (Union by Rank)<br\/>    if (subsets[xroot].rank &lt; subsets[yroot].rank)<br\/>        subsets[xroot].parent = yroot;<br\/>    else if (subsets[xroot].rank &gt; subsets[yroot].rank)<br\/>        subsets[yroot].parent = xroot;<br\/> <br\/>    \/\/ If ranks are same, then make one as root and increment<br\/>    \/\/ its rank by one<br\/>    else<br\/>    {<br\/>        subsets[yroot].parent = xroot;<br\/>        subsets[xroot].rank++;<br\/>    }<br\/>}<br\/> <br\/>\/\/ Compare two edges according to their weights.<br\/>\/\/ Used in qsort() for sorting an array of edges<br\/>int myComp(const void* a, const void* b)<br\/>{<br\/>    struct Edge* a1 = (struct Edge*)a;<br\/>    struct Edge* b1 = (struct Edge*)b;<br\/>    return a1-&gt;weight &gt; b1-&gt;weight;<br\/>}<br\/> <br\/>\/\/ The main function to construct MST using Kruskal&#039;s algorithm<br\/>void KruskalMST(struct Graph* graph)<br\/>{<br\/>    int V = graph-&gt;V;<br\/>    struct Edge result[V];  \/\/ Tnis will store the resultant MST<br\/>    int e = 0;  \/\/ An index variable, used for result[]<br\/>    int i = 0;  \/\/ An index variable, used for sorted edges<br\/> <br\/>    \/\/ Step 1:  Sort all the edges in non-decreasing order of their weight<br\/>    \/\/ If we are not allowed to change the given graph, we can create a copy of<br\/>    \/\/ array of edges<br\/>    qsort(graph-&gt;edge, graph-&gt;E, sizeof(graph-&gt;edge[0]), myComp);<br\/> <br\/>    \/\/ Allocate memory for creating V ssubsets<br\/>    struct subset *subsets =<br\/>        (struct subset*) malloc( V * sizeof(struct subset) );<br\/> <br\/>    \/\/ Create V subsets with single elements<br\/>    for (int v = 0; v &lt; V; ++v)<br\/>    {<br\/>        subsets[v].parent = v;<br\/>        subsets[v].rank = 0;<br\/>    }<br\/> <br\/>    \/\/ Number of edges to be taken is equal to V-1<br\/>    while (e &lt; V - 1)<br\/>    {<br\/>        \/\/ Step 2: Pick the smallest edge. And increment the index<br\/>        \/\/ for next iteration<br\/>        struct Edge next_edge = graph-&gt;edge[i++];<br\/> <br\/>        int x = find(subsets, next_edge.src);<br\/>        int y = find(subsets, next_edge.dest);<br\/> <br\/>        \/\/ If including this edge does&#039;t cause cycle, include it<br\/>        \/\/ in result and increment the index of result for next edge<br\/>        if (x != y)<br\/>        {<br\/>            result[e++] = next_edge;<br\/>            Union(subsets, x, y);<br\/>        }<br\/>        \/\/ Else discard the next_edge<br\/>    }<br\/> <br\/>    \/\/ print the contents of result[] to display the built MST<br\/>    printf(&quot;Following are the edges in the constructed MST\\n&quot;);<br\/>    for (i = 0; i &lt; e; ++i)<br\/>        printf(&quot;%d -- %d == %d\\n&quot;, result[i].src, result[i].dest,<br\/>                                                   result[i].weight);<br\/>    return;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/* Let us create following weighted graph<br\/>             10<br\/>        0--------1<br\/>        |  \\     |<br\/>       6|   5\\   |15<br\/>        |      \\ |<br\/>        2--------3<br\/>            4       *\/<br\/>    int V = 4;  \/\/ Number of vertices in graph<br\/>    int E = 5;  \/\/ Number of edges in graph<br\/>    struct Graph* graph = createGraph(V, E);<br\/> <br\/> <br\/>    \/\/ add edge 0-1<br\/>    graph-&gt;edge[0].src = 0;<br\/>    graph-&gt;edge[0].dest = 1;<br\/>    graph-&gt;edge[0].weight = 10;<br\/> <br\/>    \/\/ add edge 0-2<br\/>    graph-&gt;edge[1].src = 0;<br\/>    graph-&gt;edge[1].dest = 2;<br\/>    graph-&gt;edge[1].weight = 6;<br\/> <br\/>    \/\/ add edge 0-3<br\/>    graph-&gt;edge[2].src = 0;<br\/>    graph-&gt;edge[2].dest = 3;<br\/>    graph-&gt;edge[2].weight = 5;<br\/> <br\/>    \/\/ add edge 1-3<br\/>    graph-&gt;edge[3].src = 1;<br\/>    graph-&gt;edge[3].dest = 3;<br\/>    graph-&gt;edge[3].weight = 15;<br\/> <br\/>    \/\/ add edge 2-3<br\/>    graph-&gt;edge[4].src = 2;<br\/>    graph-&gt;edge[4].dest = 3;<br\/>    graph-&gt;edge[4].weight = 4;<br\/> <br\/>    KruskalMST(graph);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<h4 id=\"ad-typebanner\">[ad type=&#8221;banner&#8221;]<\/h4>\n<h4 id=\"java\"><strong>JAVA<\/strong><\/h4>\n<\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program for Kruskal&#039;s algorithm to find Minimum Spanning Tree<br\/>\/\/ of a given connected, undirected and weighted graph<br\/>import java.util.*;<br\/>import java.lang.*;<br\/>import java.io.*;<br\/> <br\/>class Graph<br\/>{<br\/>    \/\/ A class to represent a graph edge<br\/>    class Edge implements Comparable&lt;Edge&gt;<br\/>    {<br\/>        int src, dest, weight;<br\/> <br\/>        \/\/ Comparator function used for sorting edges based on<br\/>        \/\/ their weight<br\/>        public int compareTo(Edge compareEdge)<br\/>        {<br\/>            return this.weight-compareEdge.weight;<br\/>        }<br\/>    };<br\/> <br\/>    \/\/ A class to represent a subset for union-find<br\/>    class subset<br\/>    {<br\/>        int parent, rank;<br\/>    };<br\/> <br\/>    int V, E;    \/\/ V-&gt; no. of vertices &amp; E-&gt;no.of edges<br\/>    Edge edge[]; \/\/ collection of all edges<br\/> <br\/>    \/\/ Creates a graph with V vertices and E edges<br\/>    Graph(int v, int e)<br\/>    {<br\/>        V = v;<br\/>        E = e;<br\/>        edge = new Edge[E];<br\/>        for (int i=0; i&lt;e; ++i)<br\/>            edge[i] = new Edge();<br\/>    }<br\/> <br\/>    \/\/ A utility function to find set of an element i<br\/>    \/\/ (uses path compression technique)<br\/>    int find(subset subsets[], int i)<br\/>    {<br\/>        \/\/ find root and make root as parent of i (path compression)<br\/>        if (subsets[i].parent != i)<br\/>            subsets[i].parent = find(subsets, subsets[i].parent);<br\/> <br\/>        return subsets[i].parent;<br\/>    }<br\/> <br\/>    \/\/ A function that does union of two sets of x and y<br\/>    \/\/ (uses union by rank)<br\/>    void Union(subset subsets[], int x, int y)<br\/>    {<br\/>        int xroot = find(subsets, x);<br\/>        int yroot = find(subsets, y);<br\/> <br\/>        \/\/ Attach smaller rank tree under root of high rank tree<br\/>        \/\/ (Union by Rank)<br\/>        if (subsets[xroot].rank &lt; subsets[yroot].rank)<br\/>            subsets[xroot].parent = yroot;<br\/>        else if (subsets[xroot].rank &gt; subsets[yroot].rank)<br\/>            subsets[yroot].parent = xroot;<br\/> <br\/>        \/\/ If ranks are same, then make one as root and increment<br\/>        \/\/ its rank by one<br\/>        else<br\/>        {<br\/>            subsets[yroot].parent = xroot;<br\/>            subsets[xroot].rank++;<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ The main function to construct MST using Kruskal&#039;s algorithm<br\/>    void KruskalMST()<br\/>    {<br\/>        Edge result[] = new Edge[V];  \/\/ Tnis will store the resultant MST<br\/>        int e = 0;  \/\/ An index variable, used for result[]<br\/>        int i = 0;  \/\/ An index variable, used for sorted edges<br\/>        for (i=0; i&lt;V; ++i)<br\/>            result[i] = new Edge();<br\/> <br\/>        \/\/ Step 1:  Sort all the edges in non-decreasing order of their<br\/>        \/\/ weight.  If we are not allowed to change the given graph, we<br\/>        \/\/ can create a copy of array of edges<br\/>        Arrays.sort(edge);<br\/> <br\/>        \/\/ Allocate memory for creating V ssubsets<br\/>        subset subsets[] = new subset[V];<br\/>        for(i=0; i&lt;V; ++i)<br\/>            subsets[i]=new subset();<br\/> <br\/>        \/\/ Create V subsets with single elements<br\/>        for (int v = 0; v &lt; V; ++v)<br\/>        {<br\/>            subsets[v].parent = v;<br\/>            subsets[v].rank = 0;<br\/>        }<br\/> <br\/>        i = 0;  \/\/ Index used to pick next edge<br\/> <br\/>        \/\/ Number of edges to be taken is equal to V-1<br\/>        while (e &lt; V - 1)<br\/>        {<br\/>            \/\/ Step 2: Pick the smallest edge. And increment the index<br\/>            \/\/ for next iteration<br\/>            Edge next_edge = new Edge();<br\/>            next_edge = edge[i++];<br\/> <br\/>            int x = find(subsets, next_edge.src);<br\/>            int y = find(subsets, next_edge.dest);<br\/> <br\/>            \/\/ If including this edge does&#039;t cause cycle, include it<br\/>            \/\/ in result and increment the index of result for next edge<br\/>            if (x != y)<br\/>            {<br\/>                result[e++] = next_edge;<br\/>                Union(subsets, x, y);<br\/>            }<br\/>            \/\/ Else discard the next_edge<br\/>        }<br\/> <br\/>        \/\/ print the contents of result[] to display the built MST<br\/>        System.out.println(&quot;Following are the edges in the constructed MST&quot;);<br\/>        for (i = 0; i &lt; e; ++i)<br\/>            System.out.println(result[i].src+&quot; -- &quot;+result[i].dest+&quot; == &quot;+<br\/>                               result[i].weight);<br\/>    }<br\/> <br\/>    \/\/ Driver Program<br\/>    public static void main (String[] args)<br\/>    {<br\/> <br\/>        \/* Let us create following weighted graph<br\/>                 10<br\/>            0--------1<br\/>            |  \\     |<br\/>           6|   5\\   |15<br\/>            |      \\ |<br\/>            2--------3<br\/>                4       *\/<br\/>        int V = 4;  \/\/ Number of vertices in graph<br\/>        int E = 5;  \/\/ Number of edges in graph<br\/>        Graph graph = new Graph(V, E);<br\/> <br\/>        \/\/ add edge 0-1<br\/>        graph.edge[0].src = 0;<br\/>        graph.edge[0].dest = 1;<br\/>        graph.edge[0].weight = 10;<br\/> <br\/>        \/\/ add edge 0-2<br\/>        graph.edge[1].src = 0;<br\/>        graph.edge[1].dest = 2;<br\/>        graph.edge[1].weight = 6;<br\/> <br\/>        \/\/ add edge 0-3<br\/>        graph.edge[2].src = 0;<br\/>        graph.edge[2].dest = 3;<br\/>        graph.edge[2].weight = 5;<br\/> <br\/>        \/\/ add edge 1-3<br\/>        graph.edge[3].src = 1;<br\/>        graph.edge[3].dest = 3;<br\/>        graph.edge[3].weight = 15;<br\/> <br\/>        \/\/ add edge 2-3<br\/>        graph.edge[4].src = 2;<br\/>        graph.edge[4].dest = 3;<br\/>        graph.edge[4].weight = 4;<br\/> <br\/>        graph.KruskalMST();<br\/>    }<br\/>}<br\/>\/\/This code is contributed by Aakash Hasija<\/code><\/pre> <\/div>\n<h4 id=\"python\"><strong>Python<\/strong><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Python<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program for Kruskal&#039;s algorithm to find Minimum Spanning Tree<br\/># of a given connected, undirected and weighted graph<br\/> <br\/>from collections import defaultdict<br\/> <br\/>#Class to represent a graph<br\/>class Graph:<br\/> <br\/>    def __init__(self,vertices):<br\/>        self.V= vertices #No. of vertices<br\/>        self.graph = [] # default dictionary to store graph<br\/>         <br\/>  <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v,w):<br\/>        self.graph.append([u,v,w])<br\/> <br\/>    # A utility function to find set of an element i<br\/>    # (uses path compression technique)<br\/>    def find(self, parent, i):<br\/>        if parent[i] == i:<br\/>            return i<br\/>        return self.find(parent, parent[i])<br\/> <br\/>    # A function that does union of two sets of x and y<br\/>    # (uses union by rank)<br\/>    def union(self, parent, rank, x, y):<br\/>        xroot = self.find(parent, x)<br\/>        yroot = self.find(parent, y)<br\/> <br\/>        # Attach smaller rank tree under root of high rank tree<br\/>        # (Union by Rank)<br\/>        if rank[xroot] &lt; rank[yroot]:<br\/>            parent[xroot] = yroot<br\/>        elif rank[xroot] &gt; rank[yroot]:<br\/>            parent[yroot] = xroot<br\/>        #If ranks are same, then make one as root and increment<br\/>        # its rank by one<br\/>        else :<br\/>            parent[yroot] = xroot<br\/>            rank[xroot] += 1<br\/> <br\/>    # The main function to construct MST using Kruskal&#039;s algorithm<br\/>    def KruskalMST(self):<br\/> <br\/>        result =[] #This will store the resultant MST<br\/> <br\/>        i = 0 # An index variable, used for sorted edges<br\/>        e = 0 # An index variable, used for result[]<br\/> <br\/>        #Step 1:  Sort all the edges in non-decreasing order of their<br\/>        # weight.  If we are not allowed to change the given graph, we<br\/>        # can create a copy of graph<br\/>        self.graph =  sorted(self.graph,key=lambda item: item[2])<br\/>        #print self.graph<br\/> <br\/>        parent = [] ; rank = []<br\/> <br\/>        # Create V subsets with single elements<br\/>        for node in range(self.V):<br\/>            parent.append(node)<br\/>            rank.append(0)<br\/>     <br\/>        # Number of edges to be taken is equal to V-1<br\/>        while e &lt; self.V -1 :<br\/> <br\/>            # Step 2: Pick the smallest edge and increment the index<br\/>            # for next iteration<br\/>            u,v,w =  self.graph[i]<br\/>            i = i + 1<br\/>            x = self.find(parent, u)<br\/>            y = self.find(parent ,v)<br\/> <br\/>            # If including this edge does&#039;t cause cycle, include it<br\/>            # in result and increment the index of result for next edge<br\/>            if x != y:<br\/>                e = e + 1  <br\/>                result.append([u,v,w])<br\/>                self.union(parent, rank, x, y)          <br\/>            # Else discard the edge<br\/> <br\/>        # print the contents of result[] to display the built MST<br\/>        print &quot;Following are the edges in the constructed MST&quot;<br\/>        for u,v,weight  in result:<br\/>            #print str(u) + &quot; -- &quot; + str(v) + &quot; == &quot; + str(weight)<br\/>            print (&quot;%d -- %d == %d&quot; % (u,v,weight))<br\/> <br\/> <br\/>g = Graph(4)<br\/>g.addEdge(0, 1, 10)<br\/>g.addEdge(0, 2, 6)<br\/>g.addEdge(0, 3, 5)<br\/>g.addEdge(1, 3, 15)<br\/>g.addEdge(2, 3, 4)<br\/> <br\/>g.KruskalMST()<br\/> <br\/>#This code is contributed by Neelam Yadav<\/code><\/pre> <\/div>\n<pre>Following are the edges in the constructed MST\r\n2 -- 3 == 4\r\n0 -- 3 == 5\r\n0 -- 1 == 10<\/pre>\n<p><strong>Time Complexity:<\/strong> O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time. After sorting, we iterate through all edges and apply find-union algorithm. The find and union operations can take atmost O(LogV) time. So overall complexity is O(ELogE + ELogV) time. The value of E can be atmost O(V<sup>2<\/sup>), so O(LogV) are O(LogE) same. Therefore, overall time complexity is O(ElogE) or O(ElogV)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Kruskal\u2019s Minimum Spanning Tree Algorithm-Greedy 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<\/p>\n","protected":false},"author":1,"featured_media":25352,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[70144],"tags":[70802,70807,70598,70796,70799,70764,70769,70783,70784,70754,70774,70794,70781,70772,70806,70805,70767,70793,70795,70779,70766,70792,70763,70770,70775,70785,70804,70778,70776,70801,70777,70786,70773,70046,70765,70791,70797,70798,70771,70803,70788,70782],"class_list":["post-24968","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-greedy-algorithm","tag-complexity-of-kruskal-algorithm","tag-complexity-of-prims-algorithm","tag-graph-algorithms","tag-kruskal","tag-kruskal-algo","tag-kruskal-algorithm","tag-kruskal-algorithm-example","tag-kruskal-algorithm-in-c","tag-kruskal-program-in-c","tag-kruskals-algorithm","tag-kruskals-algorithm-c","tag-kruskals-algorithm-example","tag-kruskals-algorithm-in-c","tag-kruskals-algorithm-minimum-spanning-tree","tag-maximum-spanning-tree","tag-minimum-cost-spanning-tree","tag-minimum-spanning-tree","tag-minimum-spanning-tree-algorithm","tag-minimum-spanning-tree-example","tag-minimum-spanning-tree-prims-algorithm","tag-prim","tag-prim-algorithm","tag-prims-algorithm","tag-prims-algorithm-example","tag-prims-algorithm-for-minimum-spanning-tree","tag-prims-algorithm-in-c","tag-prims-algorithm-minimum-spanning-tree","tag-prims-algorithm-pseudocode","tag-prims-algorithm-with-example","tag-prims-and-kruskal-algorithm","tag-prims-and-kruskal-algorithm-with-example","tag-prims-program-in-c","tag-prism-algorithm","tag-quicksort","tag-spanning-tree","tag-spanning-tree-algorithm","tag-spanning-tree-example","tag-spanning-tree-in-data-structure","tag-time-complexity-of-kruskal-algorithm","tag-tree-algorithms","tag-what-is-span","tag-what-is-spanning-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/24968","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=24968"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/24968\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/25352"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=24968"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=24968"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=24968"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}