Skip to content

Commit 9c63473

Browse files
laishawadhwacclauss
authored andcommitted
added fibonacci_search.py (#1341)
* added fibonacci_search.py * added Fibonacci_search.py after error handling * added doctests
1 parent b7fb063 commit 9c63473

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

searches/fibonacci_search.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#run using python fibonacci_search.py -v
2+
3+
'''
4+
@params
5+
arr: input array
6+
val: the value to be searched
7+
output: the index of element in the array or -1 if not found
8+
return 0 if input array is empty
9+
'''
10+
def fibonacci_search(arr, val):
11+
12+
"""
13+
>>> fibonacci_search([1,6,7,0,0,0], 6)
14+
1
15+
>>> fibonacci_search([1,-1, 5, 2, 9], 10)
16+
-1
17+
>>> fibonacci_search([], 9)
18+
0
19+
"""
20+
fib_N_2 = 0
21+
fib_N_1 = 1
22+
fibNext = fib_N_1 + fib_N_2
23+
length = len(arr)
24+
if length == 0:
25+
return 0
26+
while (fibNext < len(arr)):
27+
fib_N_2 = fib_N_1
28+
fib_N_1 = fibNext
29+
fibNext = fib_N_1 + fib_N_2
30+
index = -1;
31+
while (fibNext > 1):
32+
i = min(index + fib_N_2, (length-1))
33+
if (arr[i] < val):
34+
fibNext = fib_N_1
35+
fib_N_1 = fib_N_2
36+
fib_N_2 = fibNext - fib_N_1
37+
index = i
38+
elif (arr[i] > val):
39+
fibNext = fib_N_2
40+
fib_N_1 = fib_N_1 - fib_N_2
41+
fib_N_2 = fibNext - fib_N_1
42+
else :
43+
return i
44+
if (fib_N_1 and index < length-1) and (arr[index+1] == val):
45+
return index+1;
46+
return -1
47+
48+
if __name__ == "__main__":
49+
import doctest
50+
doctest.testmod()

0 commit comments

Comments
 (0)