Skip to content

Commit d8beabb

Browse files
authored
Merge pull request #35 from tesla2101/master
Fibonacci Search Added
2 parents 280509f + ab41b03 commit d8beabb

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Searching/FibonacciSearch.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
//Fibonacci Search
2+
import java.util.*;
3+
4+
class FibonacciSearch
5+
{
6+
// Find minimum of two elements
7+
public static int min(int x, int y)
8+
{
9+
return (x <= y)? x : y;
10+
}
11+
12+
/* Returns index of x if present, else returns -1 */
13+
public static int fibMonaccianSearch(int arr[], int x, int n)
14+
{
15+
/* Initialize fibonacci numbers */
16+
int fibMMm2 = 0; // (m-2)'th Fibonacci No.
17+
int fibMMm1 = 1; // (m-1)'th Fibonacci No.
18+
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
19+
20+
/* fibM is going to store the smallest
21+
Fibonacci Number greater than or equal to n */
22+
while (fibM < n)
23+
{
24+
fibMMm2 = fibMMm1;
25+
fibMMm1 = fibM;
26+
fibM = fibMMm2 + fibMMm1;
27+
}
28+
29+
// Marks the eliminated range from front
30+
int offset = -1;
31+
32+
/* while there are elements to be inspected.
33+
Note that we compare arr[fibMm2] with x.
34+
When fibM becomes 1, fibMm2 becomes 0 */
35+
while (fibM > 1)
36+
{
37+
// Check if fibMm2 is a valid location
38+
int i = min(offset+fibMMm2, n-1);
39+
40+
/* If x is greater than the value at
41+
index fibMm2, cut the subarray array
42+
from offset to i */
43+
if (arr[i] < x)
44+
{
45+
fibM = fibMMm1;
46+
fibMMm1 = fibMMm2;
47+
fibMMm2 = fibM - fibMMm1;
48+
offset = i;
49+
}
50+
51+
/* If x is greater than the value at index
52+
fibMm2, cut the subarray after i+1 */
53+
else if (arr[i] > x)
54+
{
55+
fibM = fibMMm2;
56+
fibMMm1 = fibMMm1 - fibMMm2;
57+
fibMMm2 = fibM - fibMMm1;
58+
}
59+
60+
/* element found. return index */
61+
else return i;
62+
}
63+
64+
/* comparing the last element with x */
65+
if(fibMMm1 == 1 && arr[offset+1] == x)
66+
return offset+1;
67+
68+
/*element not found. return -1 */
69+
return -1;
70+
}
71+
72+
73+
public static void main(String[] args)
74+
{
75+
int arr[] = {10, 22, 35, 40, 45, 50, 80, 82};
76+
int n = arr.length;
77+
int x = 35;
78+
System.out.print ("Found at index: "+ fibMonaccianSearch(arr, x, n));
79+
}
80+
}
81+

0 commit comments

Comments
 (0)