Skip to content

Commit 3f4ba78

Browse files
committed
Modified while and for loop to fix the infinite loop and negative indices issues, respectively
1 parent e63ba4b commit 3f4ba78

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,18 @@ public <T extends Comparable<T>> int find(T[] array, T key) {
4141

4242
int limit = blockSize;
4343
// Jumping ahead to find the block where the key may be located
44-
while (limit < length && key.compareTo(array[limit]) > 0) {
45-
limit = Math.min(limit + blockSize, length - 1);
44+
while (limit < length && key.compareTo(array[Math.min(limit, length - 1)]) > 0) {
45+
limit += blockSize;
4646
}
4747

48+
// Handle the case where limit exceeds array length
49+
limit = Math.min(limit, length);
50+
4851
// Perform linear search within the identified block
4952
for (int i = limit - blockSize; i <= limit && i < length; i++) {
53+
if (i < 0) { // Skip negative indices
54+
continue;
55+
}
5056
if (array[i].equals(key)) {
5157
return i;
5258
}

0 commit comments

Comments
 (0)