Skip to content

Commit 9a26351

Browse files
fibonacci_search
1 parent 5422691 commit 9a26351

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#Made by SHASHANK CHAKRAWARTY
2+
# Python3 program for Fibonacci search.
3+
'''
4+
Works for sorted arrays
5+
A Divide and Conquer Algorithm.
6+
Has Log n time complexity.
7+
8+
1)Fibonacci Search divides given array in unequal parts
9+
10+
'''
11+
12+
#Given a sorted array arr[] of size n and an element x to be searched in it. Return index of x if it is present in array else return -1.
13+
14+
15+
16+
from bisect import bisect_left
17+
18+
def fibMonaccianSearch(arr, x, n):
19+
20+
# Initialize fibonacci numbers
21+
22+
var2 = 0 # (m-2)'th Fibonacci No.
23+
var1 = 1 # (m-1)'th Fibonacci No.
24+
res = var2 + var1 # m'th Fibonacci
25+
26+
27+
# fibM is going to store the smallest
28+
# Fibonacci Number greater than or equal to n
29+
30+
while (res < n):
31+
var2 = var1
32+
var1 = res
33+
res = var2 + var1
34+
35+
# Marks the eliminated range from front
36+
offset = -1;
37+
38+
# while there are elements to be inspected.
39+
# Note that we compare arr[var2] with x.
40+
# When fibM becomes 1, var2 becomes 0
41+
42+
43+
while (res > 1):
44+
45+
# Check if var2 is a valid location
46+
i = min(offset+var2, n-1)
47+
48+
# If x is greater than the value at
49+
# index var2, cut the subarray array
50+
# from offset to i
51+
if (arr[i] < x):
52+
res = var1
53+
var1 = var2
54+
var2 = res - var1
55+
offset = i
56+
57+
# If x is greater than the value at
58+
# index var2, cut the subarray
59+
# after i+1
60+
elif (arr[i] > x):
61+
res = var2
62+
var1 = var1 - var2
63+
var2 = res - var1
64+
65+
# element found. return index
66+
else :
67+
return i
68+
69+
# comparing the last element with x */
70+
if(var1 and arr[offset+1] == x):
71+
return offset+1;
72+
73+
# element not found. return -1
74+
return -1
75+
76+
# Driver Code, you can change the values accordingly
77+
arr = [10, 22, 35, 40, 45, 50,
78+
80, 82, 85, 90, 100]
79+
n = len(arr)
80+
x = 85
81+
print("Found at index:",
82+
fibMonaccianSearch(arr, x, n))
83+

0 commit comments

Comments
 (0)