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
Codecov Report
:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 78.56%. Comparing base (f693c44) to head (db6f72c).
:warning: Report is 2 commits behind head on master.
Additional details and impacted files
@@ Coverage Diff @@
## master #7102 +/- ##
============================================
+ Coverage 78.50% 78.56% +0.05%
- Complexity 6752 6757 +5
============================================
Files 759 759
Lines 22402 22403 +1
Branches 4400 4402 +2
============================================
+ Hits 17587 17600 +13
+ Misses 4109 4099 -10
+ Partials 706 704 -2
:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.
:rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
This pull request has been automatically closed because its workflows or checks failed and it has been inactive for more than 14 days. Please fix the workflows and reopen if you'd like to continue. Merging from main/master alone does not count as activity.