Skip to content

Commit 54fa2ea

Browse files
committed
Fibonacci Search
1 parent 081d8b1 commit 54fa2ea

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Search/FibonacciSearch/main.c

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#include <stdio.h>
2+
3+
int FibonacciSearch(int A[] , int n , int key){
4+
// Generate Fibonacci Sequence until F(k) >= n
5+
int fibk_2 = 0; // f(k-2);
6+
int fibk_1 = 1; // f(k-1);
7+
int fibk = fibk_1 + fibk_2;
8+
9+
while(fibk < n){
10+
fibk_2 = fibk_1;
11+
fibk_1 = fibk;
12+
fibk = fibk_1 + fibk_2;
13+
}
14+
15+
// initialzie variable
16+
int offset = -1; // offset for the index
17+
int i;
18+
19+
while(fibk > 1){
20+
// Calculate the index to be checked
21+
i = (offset + fibk_2 < n-1) ? offset + fibk_2 : n-1; // finding the min index
22+
23+
// Compare with the target element
24+
if(A[i] == key){
25+
return i;
26+
}else if(key > A[i]){
27+
// Move left in the Fibonacci sequence k = k-1
28+
fibk = fibk_1;
29+
fibk_1 = fibk_2;
30+
fibk_2 = fibk - fibk_1;
31+
offset = i;
32+
}else {
33+
// Move two steps left in the Fibonacci sequence k = k-2
34+
fibk = fibk_2;
35+
fibk_1 = fibk_1 - fibk_2;
36+
fibk_2 = fibk - fibk_1;
37+
}
38+
}
39+
40+
// checking the last element manually
41+
if(fibk_1 && offset+1 < n && A[offset +1 ] == key){
42+
return offset + 1;
43+
}
44+
45+
return -1; // unseccussfull search
46+
}
47+
48+
49+
int main(){
50+
int A[] = {5 , 6 , 7 , 8 , 9};
51+
int n = sizeof(A) / sizeof(A[0]);
52+
53+
int result = FibonacciSearch(A , n , 9);
54+
55+
if(result == -1){
56+
printf("%d" , result);
57+
}else{
58+
printf("%d" , result);
59+
}
60+
return 0;
61+
}

0 commit comments

Comments
 (0)