Java
Java copied to clipboard
Add kruskal algorithm
Description
This PR adds an implementation of Kruskal's Algorithm for finding the Minimum Spanning Tree (MST) in weighted undirected graphs. This addresses the feature request in issue #7067.
Kruskal's algorithm is a fundamental graph algorithm that builds the MST by sorting edges by weight and adding them one by one, using a Union-Find data structure to avoid creating cycles.
Changes Made
- ✅ Added
Kruskal.java- Complete implementation with Union-Find optimization - ✅ Added
KruskalTest.java- Comprehensive test suite with 9 test cases covering various scenarios - ✅ Documentation - Included detailed JavaDoc comments explaining the algorithm
- ✅ Optimizations - Implemented path compression and union by rank for efficiency
Algorithm Details
- Time Complexity: O(E log E) where E is the number of edges
- Space Complexity: O(V + E) where V is the number of vertices
- Key Features:
- Uses Disjoint Set (Union-Find) for efficient cycle detection
- Sorts edges by weight using Java's built-in sorting
- Handles edge cases like disconnected graphs and empty inputs
Testing
All tests pass successfully and cover:
- ✅ Simple connected graphs
- ✅ Disconnected components
- ✅ Complete graphs
- ✅ Graphs with equal-weight edges
- ✅ Edge cases (empty graphs, single edges)
- ✅ Input validation (null checks, invalid vertex counts)
References
Fixes #7067
Checklist
- [x] I have read CONTRIBUTING.md
- [x] This pull request is all my own work -- I have not plagiarized it
- [x] All filenames are in PascalCase
- [x] All functions and variable names follow Java naming conventions
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations
- [x] All new code is formatted with
mvn spotless:apply