Kruskal's Minimum Spanning Tree (MST) in C++ — Union-Find Approach

Explore this blog post in detail

Blog Images

3 images
Blog Images - Image 1
Swipe
1 / 3

Kruskal's Minimum Spanning Tree (MST) in C++ — Union-Find Approach

Mashrur Rahman
8/12/2025
Graph Algorithms
Published
# Kruskal's Algorithm — Minimum Spanning Tree (C++) ## Introduction Kruskal builds a Minimum Spanning Tree (MST) by sorting all edges by weight and adding edges in ascending order if they do not create a cycle. Cycle detection is efficiently implemented with a Disjoint Set Union (Union-Find). ## Steps 1. Sort edges by weight. 2. Iterate edges; for each `(u,v,w)`, if `find(u) != find(v)` then union them and include edge in MST. 3. Continue until MST contains `V-1` edges. ## Complexity - Sorting: **O(E log E)** - Union-Find operations: ~**O(E α(V))** (α is inverse-Ackermann) - Overall: **O(E log E)** ## Reference implementation notes File: `https://github.com/mashrur-rahman-fahim/algorithm/blob/main/Kruskal.cpp` The repo uses a `find` helper (recursive). For production, ensure path compression & union by rank/size for efficiency. ### Minimal pseudo-snippet ```cpp\nsort(edges.begin(), edges.end()); // by weight for (edge : edges) { if (find(edge.u) != find(edge.v)) { union(edge.u, edge.v); mst.push_back(edge); cost += edge.w; } }\n``` ## Pitfalls - If `find` lacks path compression, performance degrades for large graphs. - Input indexing differences (0 vs 1 based) — normalize. ## Source `https: //github.com/mashrur-rahman-fahim/algorithm/blob/main/Kruskal.cpp`

Technologies & Tools

C++Graph AlgorithmsKruskalDSUVS CodeG++ CompilerGitGitHub

About the Author

External Links

Blog Info

Status:Published
Type:Algorithm Analysis
Category:Graph Algorithms
Author:Mashrur Rahman
Created:8/12/2025

About the Author

M

Mashrur Rahman

Blog Author

Comments (0)

No comments yet. Be the first to comment!

Mashrur Rahman

A passionate full-stack developer dedicated to creating innovative digital solutions that make a difference. Let's build something amazing together.

Get In Touch

Email

mashrur9550@gmail.com

Location

Dhaka, Bangladesh

© 2026 Mashrur Rahman. All rights reserved.