Skip to content

Commit c54d796

Browse files
authored
Merge pull request #7 from spliitzx/binary-search
binary search in python3
2 parents e1f6af1 + 6e04240 commit c54d796

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Algorithms/Search/binary_search.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
Binary Search Implementation using recursion
3+
"""
4+
5+
def binary_search(arr, x, y, z):
6+
if y >= x:
7+
mid = 1 + (y-1)//2
8+
9+
if arr[mid] == z:
10+
return mid
11+
elif arr[mid] > z:
12+
return binary_search(arr, x, mid-1, z)
13+
else:
14+
return binary_search(arr, mid+1, y, z)
15+
16+
else:
17+
return -1
18+
19+
20+
# tests
21+
22+
arr = [10, 20, 30, 100, 40, 200]
23+
z = 100
24+
25+
ret = binary_search(arr, 0, len(arr)-1, z)
26+
print(ret)
27+

0 commit comments

Comments
 (0)