Kruskal's Algorithm in C

Advanced
6 min read
Updated: Nov 2026
1 example

Sorting Edges and Merging Components

Kruskal's algorithm sorts all edges by weight and scans them from cheapest to most expensive, adding an edge only if it connects two different components. A union-find (disjoint-set) structure answers "are these already connected?" quickly. Time is dominated by sorting: O(E log E). It works well on sparse graphs.

Remember
sort edges by weight
for each edge (u, v, w) in order:
    if find(u) != find(v): add edge; union(u, v)
    else: skip (would form a cycle)

Cheat Sheet

Keep these facts handy while you work with Kruskal's Algorithm in C in C.

TopicDetail
SortEdges by weight
Union-findDetects cycles
TimeO(E log E)
Good forSparse graphs

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Algorithm Techniques.

Example 1 — Kruskal with union-find

The same graph as the Prim example.

C
#include <stdio.h>
#include <stdlib.h>

struct Edge { int u, v, w; };

static int parent[5];

static int find(int x) {
    while (parent[x] != x) x = parent[x];
    return x;
}

static int by_weight(const void *a, const void *b) {
    return ((const struct Edge *)a)->w - ((const struct Edge *)b)->w;
}

int main(void) {
    struct Edge e[] = {
        {0, 3, 6}, {1, 2, 3}, {0, 1, 2}, {3, 4, 9},
        {1, 4, 5}, {2, 4, 7}, {1, 3, 8}
    };
    int m = 7, total = 0;

    for (int i = 0; i < 5; i++) parent[i] = i;
    qsort(e, m, sizeof e[0], by_weight);

    for (int i = 0; i < m; i++) {
        int ru = find(e[i].u), rv = find(e[i].v);
        if (ru != rv) {
            parent[ru] = rv;
            total += e[i].w;
            printf("add %d - %d (%d)\n", e[i].u, e[i].v, e[i].w);
        } else {
            printf("skip %d - %d (%d)\n", e[i].u, e[i].v, e[i].w);
        }
    }
    printf("total weight: %d\n", total);
    return 0;
}

How It Works

  1. After qsort, edges are processed in weight order 2, 3, 5, 6, 7, 8, 9.
  2. The first four edges join separate components, so they are added.
  3. The remaining edges would connect vertices that are already in the same component, so they are skipped. Total: 16, the same as Prim.

Edge Cases & Pitfalls

Check these before relying on Kruskal's Algorithm in C in real programs.

uf

No union-find

Checking cycles with DFS for each edge makes the algorithm slow.

sub

Comparator overflow

Subtracting weights is safe here; for large values use (a > b) - (a < b).

Key Takeaways

  • Sort edges.
  • Union-find detects cycles.
  • Stop at V - 1 edges.

One line: Kruskal's algorithm sorts all edges by weight and scans them from cheapest to most expensive, adding an edge only if it connects two different components.

Frequently Asked Questions

It processes edges in increasing weight order and adds an edge if it connects two different components, using union-find to test this.
A data structure that tracks which elements belong to the same set, with find and union operations.
Continue with "C Algorithm Techniques" next. Learn core algorithm design strategies in C: brute force, divide and conquer, greedy, dynamic programming, two pointers, and sliding windows. The C Graph Algorithms hub lists every topic in order.

Next: Algorithm Techniques

Learn core algorithm design strategies in C: brute force, divide and conquer, greedy, dynamic programming, two pointers, and sliding windows.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful