Skip to content

Commit 976cebc

Browse files
fix(searches): add null safety and Comparable consistency to JumpSearch (#7653)
1 parent 2dd1a0a commit 976cebc

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

‎src/main/java/com/thealgorithms/searches/JumpSearch.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
* @see BinarySearch
5757
* @see LinearSearch
5858
*/
59-
public class JumpSearch implements SearchAlgorithm {
59+
public final class JumpSearch implements SearchAlgorithm {
6060

6161
/**
6262
* Jump Search algorithm implementation.
@@ -67,6 +67,10 @@ public class JumpSearch implements SearchAlgorithm {
6767
*/
6868
@Override
6969
public <T extends Comparable<T>> int find(T[] array, T key) {
70+
if (array == null || array.length == 0 || key == null) {
71+
return -1;
72+
}
73+
7074
int length = array.length;
7175
int blockSize = (int) Math.sqrt(length);
7276

@@ -78,7 +82,7 @@ public <T extends Comparable<T>> int find(T[] array, T key) {
7882

7983
// Perform linear search within the identified block
8084
for (int i = limit - blockSize; i <= limit && i < length; i++) {
81-
if (array[i].equals(key)) {
85+
if (array[i] != null && key.compareTo(array[i]) == 0) {
8286
return i;
8387
}
8488
}

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,4 +139,40 @@ void testJumpSearchFindsEveryElement() {
139139
}
140140
}
141141
}
142+
143+
@Test
144+
void testJumpSearchNullArray() {
145+
JumpSearch jumpSearch = new JumpSearch();
146+
assertEquals(-1, jumpSearch.find(null, 5), "Searching in a null array should return -1.");
147+
}
148+
149+
@Test
150+
void testJumpSearchNullKey() {
151+
JumpSearch jumpSearch = new JumpSearch();
152+
Integer[] array = {1, 2, 3};
153+
assertEquals(-1, jumpSearch.find(array, null), "Searching for a null key should return -1.");
154+
}
155+
156+
@Test
157+
void testJumpSearchSingleElementAbsent() {
158+
JumpSearch jumpSearch = new JumpSearch();
159+
Integer[] array = {10};
160+
assertEquals(-1, jumpSearch.find(array, 5), "Searching for an absent key in single element array should return -1.");
161+
}
162+
163+
@Test
164+
void testJumpSearchStringArray() {
165+
JumpSearch jumpSearch = new JumpSearch();
166+
String[] array = {"apple", "banana", "cherry", "date", "elderberry"};
167+
assertEquals(2, jumpSearch.find(array, "cherry"), "The index of 'cherry' should be 2.");
168+
assertEquals(-1, jumpSearch.find(array, "fig"), "Key 'fig' should not be found.");
169+
}
170+
171+
@Test
172+
void testJumpSearchDuplicates() {
173+
JumpSearch jumpSearch = new JumpSearch();
174+
Integer[] array = {1, 2, 2, 2, 3, 4, 5};
175+
int index = jumpSearch.find(array, 2);
176+
assertEquals(2, array[index], "The element at the returned index should equal the target key.");
177+
}
142178
}

0 commit comments

Comments
 (0)