Skip to content

Commit 6511911

Browse files
Merge pull request #364 from ShubhankarKG/branchSkg
Added Fibonacci Search
2 parents 7cd99bf + 284925f commit 6511911

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#include <stdio.h>
2+
3+
4+
/*
5+
Fibonacci Search
6+
Coded by ShubhankarKG
7+
8+
Properties :
9+
1. Works with sorted arrays
10+
2. A Divide and Conquer ALgorithm
11+
3. Has Log n time complexity
12+
13+
*/
14+
15+
// Utility function that returns the minimum of two numbers
16+
int min(int a, int b){
17+
if (a <= b) return a;
18+
else return b;
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+
int fibonacciSearch(int arr[], int x, int n){
43+
int fib2 = 0;
44+
int fib1 = 1;
45+
int fibM = fib1 + fib2;
46+
47+
while(fibM<n){
48+
fib2 = fib1;
49+
fib1 = fibM;
50+
fibM = fib1 + fib2;
51+
}
52+
53+
int offset = -1;
54+
55+
while(fibM > 1){
56+
int i = 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+
else if (arr[i]>x){
66+
fibM = fib2;
67+
fib1 = fib1 - fib2;
68+
fib2 = fibM - fib1;
69+
}
70+
71+
else return i;
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));
86+
return 0;
87+
}
88+
89+
*/
131 KB
Binary file not shown.

0 commit comments

Comments
 (0)