You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Utility function that returns the minimum of two numbers
16
+
intmin(inta, intb){
17
+
if (a <= b) returna;
18
+
elsereturnb;
19
+
}
20
+
21
+
22
+
/*
23
+
Main function :
24
+
parameters :
25
+
1. Integer Array where element is to be searched
26
+
2. Integer Element that is to be searched.
27
+
3. Length of Array (n)
28
+
29
+
Find the fibonacci number just greater than n.
30
+
Find the two preceding Fibonacci numbers.
31
+
Scan all the elements in array as follows :
32
+
a. Compare element with last element of range covered by fib2
33
+
b. if x matches, return index.
34
+
c. Else if x is less than the element, move the three Fibonacci variables two Fibonacci down, indicating elimination of
35
+
approximately rear two-third of the remaining array.
36
+
d. Else x is greater than the element, move the three Fibonacci variables one Fibonacci down. Reset offset to index.
37
+
Together these indicate elimination of approximately front one-third of the remaining array.
38
+
39
+
Since there might be a single element remaining for comparison, check if fibMm1 is 1. If Yes, compare x with that remaining element. If match, return index.
40
+
41
+
*/
42
+
intfibonacciSearch(intarr[], intx, intn){
43
+
intfib2=0;
44
+
intfib1=1;
45
+
intfibM=fib1+fib2;
46
+
47
+
while(fibM<n){
48
+
fib2=fib1;
49
+
fib1=fibM;
50
+
fibM=fib1+fib2;
51
+
}
52
+
53
+
intoffset=-1;
54
+
55
+
while(fibM>1){
56
+
inti=min(offset+fib2 , n-1);
57
+
58
+
if (arr[i]<x){
59
+
fibM=fib1;
60
+
fib1=fib2;
61
+
fib2=fibM-fib1;
62
+
offset=i;
63
+
}
64
+
65
+
elseif (arr[i]>x){
66
+
fibM=fib2;
67
+
fib1=fib1-fib2;
68
+
fib2=fibM-fib1;
69
+
}
70
+
71
+
elsereturni;
72
+
}
73
+
74
+
if (fib1&&arr[offset+1] ==x) return (offset+1);
75
+
76
+
return-1;
77
+
}
78
+
79
+
/* Driver code to check search
80
+
81
+
int main(){
82
+
int arr[] = {1,2,3,4,5,6,7,8,9,11, 12,13};
83
+
int n = sizeof(arr)/sizeof(arr[1]);
84
+
int x = 6;
85
+
printf("Element found at index %d", fibonacciSearch(arr,x,n));
0 commit comments