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
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public <T extends Comparable<T>> int find(T[] array, T key) {
}
}

if (fibMinus1 == 1 && array[offset + 1] == key) {
if (fibMinus1 == 1 && offset + 1 < n && array[offset + 1].compareTo(key) == 0) {
return offset + 1;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,53 @@ void testFibonacciSearchLargeArray() {
int expectedIndex = 9999;
assertEquals(expectedIndex, fibonacciSearch.find(array, key), "The index of the last element should be 9999.");
}

/**
* A key greater than every element used to throw {@link ArrayIndexOutOfBoundsException},
* because the final probe read {@code array[offset + 1]} without checking the bound.
*/
@Test
void testFibonacciSearchKeyGreaterThanLastElement() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
for (int length = 1; length <= 50; length++) {
Integer[] array = new Integer[length];
for (int i = 0; i < length; i++) {
array[i] = i;
}
assertEquals(-1, fibonacciSearch.find(array, length), "A key above the maximum should not be found for length " + length + ".");
}
}

/**
* The final probe used reference equality, so a key that is equal but not identical to the
* stored element was reported as missing. Values above 127 are outside the {@link Integer}
* cache and therefore are not the same object as the boxed array element.
*/
@Test
void testFibonacciSearchFindsEqualButNotIdenticalKey() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Integer[] array = {10, 20, 300};
assertEquals(2, fibonacciSearch.find(array, Integer.valueOf(300)), "The index of the found element should be 2.");

String[] words = {"a", "b", "c"};
String equalButDistinct = new StringBuilder("c").toString();
assertEquals(2, fibonacciSearch.find(words, equalButDistinct), "The index of the found element should be 2.");
}

/**
* Every element must be found regardless of the array length.
*/
@Test
void testFibonacciSearchFindsEveryElement() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
for (int length = 1; length <= 50; length++) {
Integer[] array = new Integer[length];
for (int i = 0; i < length; i++) {
array[i] = 1000 + i * 2;
}
for (int i = 0; i < length; i++) {
assertEquals(i, fibonacciSearch.find(array, Integer.valueOf(1000 + i * 2)), "Element at index " + i + " should be found for length " + length + ".");
}
}
}
}
Loading