diff --git a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java index 78dac0f0a712..fa91cd14a1af 100644 --- a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java +++ b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java @@ -69,7 +69,7 @@ public > 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; } diff --git a/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java b/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java index 801c33b1d09a..04a270864223 100644 --- a/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java @@ -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 + "."); + } + } + } }