Skip to content

Commit 54b8922

Browse files
committed
Improve robustness and test coverage for Kruskal MST
1 parent 5b721b2 commit 54b8922

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

src/main/java/com/thealgorithms/graph/KruskalMST.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.ArrayList;
44
import java.util.Collections;
55
import java.util.List;
6+
import java.util.Objects;
67

78
/**
89
* Implementation of Kruskal's Algorithm to find
@@ -22,18 +23,22 @@ private KruskalMST() {
2223
* @param edges list of all edges in the graph
2324
* @return list of edges forming the MST
2425
* @throws IllegalArgumentException if vertices <= 0
26+
* @throws NullPointerException if edges is null
2527
*/
2628
public static List<Edge> findMST(final int vertices, final List<Edge> edges) {
2729
if (vertices <= 0) {
2830
throw new IllegalArgumentException("Number of vertices must be positive");
2931
}
3032

33+
Objects.requireNonNull(edges, "Edges list must not be null");
34+
35+
final List<Edge> sortedEdges = new ArrayList<>(edges);
36+
Collections.sort(sortedEdges);
37+
3138
final List<Edge> mst = new ArrayList<>();
3239
final DisjointSetUnion dsu = new DisjointSetUnion(vertices);
3340

34-
Collections.sort(edges);
35-
36-
for (final Edge edge : edges) {
41+
for (final Edge edge : sortedEdges) {
3742
final int rootU = dsu.find(edge.source);
3843
final int rootV = dsu.find(edge.destination);
3944

src/test/java/com/thealgorithms/graph/KruskalMSTTest.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
44
import static org.junit.jupiter.api.Assertions.assertNotNull;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
56

67
import java.util.ArrayList;
78
import java.util.List;
@@ -47,4 +48,31 @@ void testFindMSTWithSingleVertex() {
4748
assertNotNull(mst, "MST should not be null");
4849
assertEquals(0, mst.size(), "MST of single vertex graph should be empty");
4950
}
51+
52+
@Test
53+
void testInvalidVertexCountThrowsException() {
54+
final List<Edge> edges = new ArrayList<>();
55+
56+
assertThrows(
57+
IllegalArgumentException.class,
58+
() -> KruskalMST.findMST(0, edges),
59+
"Expected exception for non-positive vertex count"
60+
);
61+
}
62+
63+
@Test
64+
void testPathCompressionScenario() {
65+
final int vertices = 5;
66+
67+
final List<Edge> edges = new ArrayList<>();
68+
edges.add(new Edge(0, 1, 1));
69+
edges.add(new Edge(1, 2, 2));
70+
edges.add(new Edge(2, 3, 3));
71+
edges.add(new Edge(3, 4, 4));
72+
73+
final List<Edge> mst = KruskalMST.findMST(vertices, edges);
74+
75+
assertNotNull(mst);
76+
assertEquals(vertices - 1, mst.size(), "MST should contain V-1 edges");
77+
}
5078
}

0 commit comments

Comments
 (0)