Skip to content

Commit 2f20fa8

Browse files
committed
test(searches): add unit tests for LowerBound duplicate values and null safety
Verify LowerBound returns the first occurrence for duplicate elements, and handles empty arrays, null arrays, and null keys gracefully in LowerBound and UpperBound.
1 parent 492efe5 commit 2f20fa8

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

‎src/test/java/com/thealgorithms/searches/LowerBoundTest.java‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,31 @@ void testLowerBoundNonExistentValue() {
5656
assertEquals(4, lowerBound.find(array, 7), "Lower bound for 7 should be at index 4");
5757
assertEquals(0, lowerBound.find(array, 0), "Lower bound for 0 should be at index 0");
5858
}
59+
60+
/**
61+
* Test finding the lower bound for an element with duplicate occurrences.
62+
* Lower bound should point to the FIRST element not less than key.
63+
*/
64+
@Test
65+
void testLowerBoundDuplicates() {
66+
LowerBound lowerBound = new LowerBound();
67+
Integer[] arrayWithDuplicates = {1, 2, 2, 2, 3, 4, 5};
68+
69+
assertEquals(1, lowerBound.find(arrayWithDuplicates, 2), "Lower bound for 2 should be at index 1 (first occurrence)");
70+
71+
Integer[] allSame = {2, 2, 2, 2, 2};
72+
assertEquals(0, lowerBound.find(allSame, 2), "Lower bound for 2 in all-same array should be at index 0");
73+
}
74+
75+
/**
76+
* Test edge cases: empty array, null array, and null key.
77+
*/
78+
@Test
79+
void testLowerBoundNullAndEmptyEdgeCases() {
80+
LowerBound lowerBound = new LowerBound();
81+
Integer[] emptyArray = {};
82+
assertEquals(0, lowerBound.find(emptyArray, 5), "Lower bound for an empty array should be 0");
83+
assertEquals(0, lowerBound.find(null, 5), "Lower bound for a null array should be 0");
84+
assertEquals(0, lowerBound.find(new Integer[] {1, 2, 3}, null), "Lower bound for a null key should be 0");
85+
}
5986
}

‎src/test/java/com/thealgorithms/searches/UpperBoundTest.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,10 @@ void testUpperBoundSingleElementArray() {
9696
index = upperBound.find(singleElementArray, 15);
9797
assertEquals(0, index, "Upper bound for 15 in a single element array should be 0.");
9898
}
99+
100+
@Test
101+
void testUpperBoundNullArrayAndKey() {
102+
assertEquals(0, upperBound.find(null, 5), "Upper bound for a null array should be 0.");
103+
assertEquals(0, upperBound.find(new Integer[] {1, 2, 3}, null), "Upper bound for a null key should be 0.");
104+
}
99105
}

0 commit comments

Comments
 (0)