DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS

Find a Minimum Spanning Tree with Kruskal's Algorithm

Learn how to find a minimum spanning tree with kruskal's algorithm using a clear C program.

AdvancedKruskalMinimum spanning treeDSU

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
2-3(4) 0-3(5) 0-1(10)
Cost = 19

COMPLETE C PROGRAM

Complete C implementation

dsa-kruskal-minimum-spanning-tree.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Edge { int source; int destination; int weight; };
int compare_edges(const void *left, const void *right)
{
    const struct Edge *first = left, *second = right;
    return (first->weight > second->weight) - (first->weight < second->weight);
}
int find(int parent[], int value)
{
    if (parent[value] != value) parent[value] = find(parent, parent[value]);
    return parent[value];
}

int main(void)
{
    struct Edge edges[] = {{0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4}};
    qsort(edges, 5, sizeof edges[0], compare_edges);
    int parent[] = {0, 1, 2, 3}, selected = 0, cost = 0;
    for (int index = 0; index < 5 && selected < 3; index++) {
        int first = find(parent, edges[index].source);
        int second = find(parent, edges[index].destination);
        if (first != second) {
            parent[second] = first; cost += edges[index].weight; selected++;
            printf("%d-%d(%d) ", edges[index].source, edges[index].destination, edges[index].weight);
        }
    }
    printf("\nCost = %d\n", cost);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

2-3(4) 0-3(5) 0-1(10)
Cost = 19
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Process edges from smallest weight upward and accept only edges joining different sets.
  3. Display the computed result.

Process edges from smallest weight upward and accept only edges joining different sets.

EFFICIENCY

Time and space complexity

Time complexity

O(E log E)

Auxiliary space

O(V)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.