-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathfibonacciSearch.c
74 lines (59 loc) · 1.09 KB
/
fibonacciSearch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
C program for Fibonacci Search
*/
#include <stdio.h>
/*
Function to return the index of x in arr
Time Complexity : O(logn)
*/
int fibonacciSearch(int arr[], int x, int n)
{
int l = 0;
int r = 1;
int sum = l + r;
while (sum < n)
{
l = r;
r = sum;
sum = l + r;
}
int offset = -1;
while (sum > 1)
{
int i;
if (offset + l < n - 1)
{
i = offset + l;
}
else
{
i = n - 1;
}
if (arr[i] < x)
{
sum = r;
r = l;
l = sum - r;
offset = i;
}
else if (arr[i] > x)
{
sum = r;
r = r - l;
l = sum - r;
}
else
return i;
}
if (l && arr[offset + 1] == x)
return offset + 1;
return -1;
}
int main()
{
int arr[] = {2, 3, 4, 7, 9, 13, 17, 21};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 13;
printf("Index of %d in arr is %d\n", x, fibonacciSearch(arr, x, n));
return 0;
}