C Example: Union-Find: path compression, union by rank and components

🗓 Last updated: 2026-11-30👤 Written by: Harper✓ Reviewed by: Alex🏷 Category: Algorithms

Implements a 10-element union-find: find compresses paths recursively, unite merges by rank and maintains a component count. Runs seven unions (including a self-union and an already-connected pair), queries four connectivity pairs, then prints the parent array and remaining components.

🔥 Advanced Reference entries: kw-structkw-intfn-printf
🖥 Run OnlineGCC 10.2 · C11 standard · click ▶ to run · Copy code
🖨 Reference OutputMatches the online run in a standard C11 environment
C · GCC 10.2 · -std=c11
union(0,1) -> merged
union(2,3) -> merged
union(1,3) -> merged
union(4,5) -> merged
union(6,7) -> merged
union(8,8) -> already same
union(5,2) -> merged
parent: 0 0 0 2 0 4 6 6 8 9
components: 4
connected(0,3): yes
connected(0,4): yes
connected(6,7): yes
connected(9,0): no
🧩 Keep Learning

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏