Skip to content

Commit 1280321

Browse files
Add Fibonacci Search (TheAlgorithms#2698)
1 parent c59d125 commit 1280321

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Searches/FibonacciSearch.java

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package Searches;
2+
3+
/*
4+
* Fibonacci Search is a popular algorithm which finds the position of a target value in
5+
* a sorted array
6+
*
7+
* The time complexity for this search algorithm is O(log3(n))
8+
* The space complexity for this search algorithm is O(1)
9+
* @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru)
10+
*/
11+
public class FibonacciSearch implements SearchAlgorithm {
12+
/**
13+
* @param array is a sorted array where the element has to be searched
14+
* @param key is an element whose position has to be found
15+
* @param <T> is any comparable type
16+
* @return index of the element
17+
*/
18+
@Override
19+
public <T extends Comparable<T>> int find(T[] array, T key) {
20+
int fibMinus1 = 1;
21+
int fibMinus2 = 0;
22+
int fibNumber = fibMinus1 + fibMinus2;
23+
int n = array.length;
24+
25+
while (fibNumber < n) {
26+
fibMinus2 = fibMinus1;
27+
fibMinus1 = fibNumber;
28+
fibNumber = fibMinus2 + fibMinus1;
29+
}
30+
31+
int offset = -1;
32+
33+
while (fibNumber > 1) {
34+
int i = Math.min(offset + fibMinus2, n - 1);
35+
36+
if (array[i].compareTo(key) < 0) {
37+
fibNumber = fibMinus1;
38+
fibMinus1 = fibMinus2;
39+
fibMinus2 = fibNumber - fibMinus1;
40+
offset = i;
41+
}
42+
else if (array[i].compareTo(key) > 0) {
43+
fibNumber = fibMinus2;
44+
fibMinus1 = fibMinus1 - fibMinus2;
45+
fibMinus2 = fibNumber - fibMinus1;
46+
}
47+
else {
48+
return i;
49+
}
50+
}
51+
52+
if (fibMinus1 == 1 && array[offset + 1] == key) {
53+
return offset + 1;
54+
}
55+
56+
return -1;
57+
}
58+
59+
// Driver Program
60+
public static void main(String[] args) {
61+
Integer[] integers = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
62+
63+
int size = integers.length;
64+
Integer shouldBeFound = 128;
65+
FibonacciSearch fsearch = new FibonacciSearch();
66+
int atIndex = fsearch.find(integers, shouldBeFound);
67+
68+
System.out.println(
69+
"Should be found: " + shouldBeFound + ". Found "+ integers[atIndex] + " at index "+ atIndex +". An array length " + size);
70+
}
71+
72+
}

0 commit comments

Comments
 (0)