Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/main/java/com/thealgorithms/searches/JumpSearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,18 @@ public <T extends Comparable<T>> int find(T[] array, T key) {

int limit = blockSize;
// Jumping ahead to find the block where the key may be located
while (limit < length && key.compareTo(array[limit]) > 0) {
limit = Math.min(limit + blockSize, length - 1);
while (limit < length && key.compareTo(array[Math.min(limit, length - 1)]) > 0) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Math.min in while (limit < length && key.compareTo(array[Math.min(limit, length - 1)]) > 0) is a bit redundant because you already check limit < length in the while condition.

So it can be simplified to:

while (limit < length && key.compareTo(array[limit]) > 0) {
    limit += blockSize;
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add your test case, with infinite loop, to com.thealgorithms.searches.JumpSearchTest

limit += blockSize;
}

// Handle the case where limit exceeds array length
limit = Math.min(limit, length);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think to rewrite below loop to:

int start = Math.max(0, limit - blockSize);
int end = Math.min(limit, length);

// Perform linear search within the identified block
for (int i = start; i < end; i++) {
    if (array[i].equals(key)) {
        return i;
    }
}


// Perform linear search within the identified block
for (int i = limit - blockSize; i <= limit && i < length; i++) {
if (i < 0) { // Skip negative indices
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like, the condition if (i < 0) continue; is unnecessary. Since limit starts at blockSize, limit - blockSize will always be >= 0.

continue;
}
if (array[i].equals(key)) {
return i;
}
Expand Down