Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion src/main/java/com/thealgorithms/searches/JumpSearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ 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);
limit += blockSize;
}

// Perform linear search within the identified block
Expand Down
48 changes: 48 additions & 0 deletions src/test/java/com/thealgorithms/searches/JumpSearchTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;

/**
* Unit tests for the JumpSearch class.
Expand Down Expand Up @@ -91,4 +93,50 @@ void testJumpSearchLargeArrayNotFound() {
Integer key = 999; // Key not present
assertEquals(-1, jumpSearch.find(array, key), "The element should not be found in the array.");
}

/**
* A key greater than every element used to make the jumping loop spin forever, because the
* cursor was clamped to the last index and therefore stopped advancing.
*/
@Test
@Timeout(value = 5, unit = TimeUnit.SECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
void testJumpSearchKeyGreaterThanLastElement() {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = {1, 2, 3, 4};
assertEquals(-1, jumpSearch.find(array, 5), "A key above the maximum should not be found.");
}

/**
* The same regression across several lengths, since the jump size depends on the array length.
*/
@Test
@Timeout(value = 5, unit = TimeUnit.SECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
void testJumpSearchKeyGreaterThanLastElementForEveryLength() {
JumpSearch jumpSearch = new JumpSearch();
for (int length = 1; length <= 50; length++) {
Integer[] array = new Integer[length];
for (int i = 0; i < length; i++) {
array[i] = i;
}
assertEquals(-1, jumpSearch.find(array, length), "A key above the maximum should not be found for length " + length + ".");
}
}

/**
* Every element must be found regardless of the array length, including the ones that sit
* exactly on a jump boundary.
*/
@Test
void testJumpSearchFindsEveryElement() {
JumpSearch jumpSearch = new JumpSearch();
for (int length = 1; length <= 50; length++) {
Integer[] array = new Integer[length];
for (int i = 0; i < length; i++) {
array[i] = i * 2;
}
for (int i = 0; i < length; i++) {
assertEquals(i, jumpSearch.find(array, i * 2), "Element at index " + i + " should be found for length " + length + ".");
}
}
}
}
Loading