Skip to content

Commit aba33a0

Browse files
Marcelo AndradeMarcelo Andrade
Marcelo Andrade
authored and
Marcelo Andrade
committed
Added Binary Search
1 parent 4b9f145 commit aba33a0

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: python/binary_search.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
def binary_search(arr, low, high, x):
2+
3+
if high >= low:
4+
5+
mid = (high + low) // 2
6+
7+
if arr[mid] == x:
8+
return mid
9+
10+
elif arr[mid] > x:
11+
return binary_search(arr, low, mid - 1, x)
12+
13+
else:
14+
return binary_search(arr, mid + 1, high, x)
15+
16+
else:
17+
return -1
18+
19+
arr = [ 2, 3, 4, 10, 40 ]
20+
x = 10
21+
22+
result = binary_search(arr, 0, len(arr)-1, x)
23+
24+
if result != -1:
25+
print("Element is present at index", str(result))
26+
else:
27+
print("Element is not present in array")

0 commit comments

Comments
 (0)