Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)
Next article icon

Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 cycle is not formed, include this edge. Else, discard it. 
  3. Repeat step#2 until there are (V-1) edges in the spanning tree.

We have discussed one implementation of Kruskal’s algorithm in previous post. In this post, a simpler implementation for adjacency matrix is discussed. 

Implementation:

C++




// Simple C++ implementation for Kruskal's
// algorithm
#include <bits/stdc++.h>
using namespace std;
 
#define V 5
int parent[V];
 
// Find set of vertex i
int find(int i)
{
    while (parent[i] != i)
        i = parent[i];
    return i;
}
 
// Does union of i and j. It returns
// false if i and j are already in same
// set.
void union1(int i, int j)
{
    int a = find(i);
    int b = find(j);
    parent[a] = b;
}
 
// Finds MST using Kruskal's algorithm
void kruskalMST(int cost[][V])
{
    int mincost = 0; // Cost of min MST.
 
    // Initialize sets of disjoint sets.
    for (int i = 0; i < V; i++)
        parent[i] = i;
 
    // Include minimum weight edges one by one
    int edge_count = 0;
    while (edge_count < V - 1) {
        int min = INT_MAX, a = -1, b = -1;
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                if (find(i) != find(j) && cost[i][j] < min) {
                    min = cost[i][j];
                    a = i;
                    b = j;
                }
            }
        }
 
        union1(a, b);
        printf("Edge %d:(%d, %d) cost:%d \n",
               edge_count++, a, b, min);
        mincost += min;
    }
    printf("\n Minimum cost= %d \n", mincost);
}
 
// driver program to test above function
int main()
{
    /* Let us create the following graph
          2    3
      (0)--(1)--(2)
       |   / \   |
      6| 8/   \5 |7
       | /     \ |
      (3)-------(4)
            9          */
    int cost[][V] = {
        { INT_MAX, 2, INT_MAX, 6, INT_MAX },
        { 2, INT_MAX, 3, 8, 5 },
        { INT_MAX, 3, INT_MAX, INT_MAX, 7 },
        { 6, 8, INT_MAX, INT_MAX, 9 },
        { INT_MAX, 5, 7, 9, INT_MAX },
    };
 
    // Print the solution
    kruskalMST(cost);
 
    return 0;
}
 
 

Java




// Simple Java implementation for Kruskal's
// algorithm
import java.util.*;
 
class GFG
{
 
static int V = 5;
static int[] parent = new int[V];
static int INF = Integer.MAX_VALUE;
 
// Find set of vertex i
static int find(int i)
{
    while (parent[i] != i)
        i = parent[i];
    return i;
}
 
// Does union of i and j. It returns
// false if i and j are already in same
// set.
static void union1(int i, int j)
{
    int a = find(i);
    int b = find(j);
    parent[a] = b;
}
 
// Finds MST using Kruskal's algorithm
static void kruskalMST(int cost[][])
{
    int mincost = 0; // Cost of min MST.
 
    // Initialize sets of disjoint sets.
    for (int i = 0; i < V; i++)
        parent[i] = i;
 
    // Include minimum weight edges one by one
    int edge_count = 0;
    while (edge_count < V - 1)
    {
        int min = INF, a = -1, b = -1;
        for (int i = 0; i < V; i++)
        {
            for (int j = 0; j < V; j++)
            {
                if (find(i) != find(j) && cost[i][j] < min)
                {
                    min = cost[i][j];
                    a = i;
                    b = j;
                }
            }
        }
 
        union1(a, b);
        System.out.printf("Edge %d:(%d, %d) cost:%d \n",
            edge_count++, a, b, min);
        mincost += min;
    }
    System.out.printf("\n Minimum cost= %d \n", mincost);
}
 
// Driver code
public static void main(String[] args)
{
/* Let us create the following graph
        2 3
    (0)--(1)--(2)
    | / \ |
    6| 8/ \5 |7
    | /     \ |
    (3)-------(4)
            9         */
    int cost[][] = {
        { INF, 2, INF, 6, INF },
        { 2, INF, 3, 8, 5 },
        { INF, 3, INF, INF, 7 },
        { 6, 8, INF, INF, 9 },
        { INF, 5, 7, 9, INF },
    };
 
    // Print the solution
    kruskalMST(cost);
    }
}
 
// This code contributed by Rajput-Ji
 
 

Python3




# Python implementation for Kruskal's
# algorithm
 
# Find set of vertex i
def find(i):
    while parent[i] != i:
        i = parent[i]
    return i
 
# Does union of i and j. It returns
# false if i and j are already in same
# set.
def union(i, j):
    a = find(i)
    b = find(j)
    parent[a] = b
 
# Finds MST using Kruskal's algorithm
def kruskalMST(cost):
    mincost = 0 # Cost of min MST
 
    # Initialize sets of disjoint sets
    for i in range(V):
        parent[i] = i
 
    # Include minimum weight edges one by one
    edge_count = 0
    while edge_count < V - 1:
        min = INF
        a = -1
        b = -1
        for i in range(V):
            for j in range(V):
                if find(i) != find(j) and cost[i][j] < min:
                    min = cost[i][j]
                    a = i
                    b = j
        union(a, b)
        print('Edge {}:({}, {}) cost:{}'.format(edge_count, a, b, min))
        edge_count += 1
        mincost += min
 
    print("Minimum cost= {}".format(mincost))
 
 
# Driver code
# Let us create the following graph
#         2 3
#     (0)--(1)--(2)
#     | / \ |
#     6| 8/ \5 |7
#     | /     \ |
#     (3)-------(4)
#         9
 
V = 5
parent = [i for i in range(V)]
INF = float('inf')
cost = [[INF, 2, INF, 6, INF],
        [2, INF, 3, 8, 5],
        [INF, 3, INF, INF, 7],
        [6, 8, INF, INF, 9],
        [INF, 5, 7, 9, INF]]
 
# Print the solution
kruskalMST(cost)
 
# This code is contributed by ng24_7
 
 

C#




// Simple C# implementation for Kruskal's
// algorithm
using System;    
 
class GFG
{
 
static int V = 5;
static int[] parent = new int[V];
static int INF = int.MaxValue;
 
// Find set of vertex i
static int find(int i)
{
    while (parent[i] != i)
        i = parent[i];
    return i;
}
 
// Does union of i and j. It returns
// false if i and j are already in same
// set.
static void union1(int i, int j)
{
    int a = find(i);
    int b = find(j);
    parent[a] = b;
}
 
// Finds MST using Kruskal's algorithm
static void kruskalMST(int [,]cost)
{
    int mincost = 0; // Cost of min MST.
 
    // Initialize sets of disjoint sets.
    for (int i = 0; i < V; i++)
        parent[i] = i;
 
    // Include minimum weight edges one by one
    int edge_count = 0;
    while (edge_count < V - 1)
    {
        int min = INF, a = -1, b = -1;
        for (int i = 0; i < V; i++)
        {
            for (int j = 0; j < V; j++)
            {
                if (find(i) != find(j) && cost[i, j] < min)
                {
                    min = cost[i, j];
                    a = i;
                    b = j;
                }
            }
        }
 
        union1(a, b);
        Console.Write("Edge {0}:({1}, {2}) cost:{3} \n",
            edge_count++, a, b, min);
        mincost += min;
    }
    Console.Write("\n Minimum cost= {0} \n", mincost);
}
 
// Driver code
public static void Main(String[] args)
{
/* Let us create the following graph
        2 3
    (0)--(1)--(2)
    | / \ |
    6| 8/ \5 |7
    | /     \ |
    (3)-------(4)
            9         */
    int [,]cost = {
        { INF, 2, INF, 6, INF },
        { 2, INF, 3, 8, 5 },
        { INF, 3, INF, INF, 7 },
        { 6, 8, INF, INF, 9 },
        { INF, 5, 7, 9, INF },
    };
 
    // Print the solution
    kruskalMST(cost);
}
}
 
/* This code contributed by PrinciRaj1992 */
 
 

Javascript




<script>
 
 
// Simple Javascript implementation for Kruskal's
// algorithm
 
 
var V = 5;
var parent = Array(V).fill(0);
var INF = 1000000000;
 
// Find set of vertex i
function find(i)
{
    while (parent[i] != i)
        i = parent[i];
    return i;
}
 
// Does union of i and j. It returns
// false if i and j are already in same
// set.
function union1(i, j)
{
    var a = find(i);
    var b = find(j);
    parent[a] = b;
}
 
// Finds MST using Kruskal's algorithm
function kruskalMST(cost)
{
    var mincost = 0; // Cost of min MST.
 
    // Initialize sets of disjoint sets.
    for (var i = 0; i < V; i++)
        parent[i] = i;
 
    // Include minimum weight edges one by one
    var edge_count = 0;
    while (edge_count < V - 1)
    {
        var min = INF, a = -1, b = -1;
        for (var i = 0; i < V; i++)
        {
            for (var j = 0; j < V; j++)
            {
                if (find(i) != find(j) && cost[i][j] < min)
                {
                    min = cost[i][j];
                    a = i;
                    b = j;
                }
            }
        }
 
        union1(a, b);
        document.write(`Edge ${edge_count++}:(${a},
        ${b}) cost:${min} <br>`);
        mincost += min;
    }
    document.write(`<br> Minimum cost= ${mincost} <br>`);
}
 
// Driver code
 
/* Let us create the following graph
        2 3
    (0)--(1)--(2)
    | / \ |
    6| 8/ \5 |7
    | /     \ |
    (3)-------(4)
            9         */
var cost = [
    [INF, 2, INF, 6, INF],
    [2, INF, 3, 8, 5],
    [INF, 3, INF, INF, 7],
    [6, 8, INF, INF, 9],
    [INF, 5, 7, 9, INF]];
// Print the solution
kruskalMST(cost);
 
 
</script>
 
 
Output
Edge 0:(0, 1) cost:2  Edge 1:(1, 2) cost:3  Edge 2:(1, 4) cost:5  Edge 3:(0, 3) cost:6    Minimum cost= 16 

Time Complexity:
The time complexity of Kruskal’s algorithm using the Union-Find algorithm for finding the cycle and sorting the edges is O(E log E + E log V), where E is the number of edges and V is the number of vertices in the graph. 

Space Complexity:
The space complexity of the program is O(V), where V is the number of vertices in the graph.

Note that the above solution is not efficient. The idea is to provide a simple implementation for adjacency matrix representations. Please see below for efficient implementations. 

Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 
Kruskal’s Minimum Spanning Tree using STL in C++



Next Article
Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)

A

AnkurKarmakar
Improve
Article Tags :
  • Algorithms
  • C Programs
  • DSA
  • Greedy
Practice Tags :
  • Algorithms
  • Greedy

Similar Reads

  • Prim's Algorithm (Simple Implementation for Adjacency Matrix Representation)
    We have discussed Prim's algorithm and its implementation for adjacency matrix representation of graphs. As discussed in the previous post, in Prim's algorithm, two sets are maintained, one set contains list of vertices already included in MST, other set contains vertices not yet included. In every
    9 min read
  • C program to implement Adjacency Matrix of a given Graph
    Given a undirected Graph of N vertices 1 to N and M edges in form of 2D array arr[][] whose every row consists of two numbers X and Y which denotes that there is a edge between X and Y, the task is to write C program to create Adjacency Matrix of the given Graph. Examples: Input: N = 5, M = 4, arr[]
    3 min read
  • C program to implement DFS traversal using Adjacency Matrix in a given Graph
    Given a undirected graph with V vertices and E edges. The task is to perform DFS traversal of the graph. Examples: Input: V = 7, E = 7Connections: 0-1, 0-2, 1-3, 1-4, 1-5, 1-6, 6-2See the diagram for connections: Output : 0 1 3 4 5 6 2Explanation: The traversal starts from 0 and follows the followin
    3 min read
  • C Program to Implement Adjacency List
    An adjacency list is a data structure used to represent a graph in the form of an array of linked lists. The index of the array represents a vertex and each element in its linked list represents the other vertices of the graph that form an edge with the vertex at the index. In this article, we will
    6 min read
  • C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
    Problem Statement: Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph. What is Dijkstra's Algorithm? Dijkstra's algorithm is very similar to Prim's algorithm for minimum spanning tree. Like Prim's MST, we generate an SPT (shorte
    5 min read
  • Check if a graph is Strongly, Unilaterally or Weakly connected
    Given an unweighted directed graph G as a path matrix, the task is to find out if the graph is Strongly Connected or Unilaterally Connected or Weakly Connected. Strongly Connected: A graph is said to be strongly connected if every pair of vertices(u, v) in the graph contains a path between each othe
    12 min read
  • C Program for Breadth First Search or BFS for a Graph
    The Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Relation between BFS for Graph and Tree
    3 min read
  • C Program for Depth First Search or DFS for a Graph
    Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS tr
    4 min read
  • C Program for Find the number of islands | Set 1 (Using DFS)
    Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands Example: Input: mat[][] = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1} Output: 5This is a variation of the standard
    3 min read
  • Construct a graph using N vertices whose shortest distance between K pair of vertices is 2
    Given two positive integers N and K, the task is to construct a simple and connected graph consisting of N vertices with the length of each edge as 1 unit, such that the shortest distance between exactly K pairs of vertices is 2. If it is not possible to construct the graph, then print -1. Otherwise
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences