Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 6 additions & 4 deletions src/main/java/com/thealgorithms/searches/FibonacciSearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,22 @@
* Note: This algorithm requires that the input array be sorted.
* </p>
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class FibonacciSearch implements SearchAlgorithm {
public final class FibonacciSearch implements SearchAlgorithm {

/**
* Finds the index of the specified key in a sorted array using Fibonacci search.
*
* @param array The sorted array to search.
* @param key The element to search for.
* @param <T> The type of the elements in the array, which must be comparable.
* @throws IllegalArgumentException if the input array is not sorted or empty, or if the key is null.
* @throws IllegalArgumentException if the input array is null, not sorted or empty, or if the key is null.
* @return The index of the key if found, otherwise -1.
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
if (array == null) {
throw new IllegalArgumentException("Input array must not be null.");
}
if (array.length == 0) {
throw new IllegalArgumentException("Input array must not be empty.");
}
Expand Down Expand Up @@ -76,7 +78,7 @@ public <T extends Comparable<T>> int find(T[] array, T key) {
return -1;
}

private boolean isSorted(Comparable[] array) {
private <T extends Comparable<T>> boolean isSorted(T[] array) {
for (int i = 1; i < array.length; i++) {
if (array[i - 1].compareTo(array[i]) > 0) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ void testFibonacciSearchEmptyArray() {
assertThrows(IllegalArgumentException.class, () -> fibonacciSearch.find(array, key), "An empty array should throw an IllegalArgumentException.");
}

/**
* Test for Fibonacci search with a null array.
*/
@Test
void testFibonacciSearchNullArray() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
assertThrows(IllegalArgumentException.class, () -> fibonacciSearch.find(null, 5), "A null array should throw an IllegalArgumentException.");
}

@Test
void testFibonacciSearchUnsortedArray() {
FibonacciSearch fibonacciSearch = new FibonacciSearch();
Expand Down
Loading