Skip to content

Commit 9056367

Browse files
committed
Created python program for binary search
1 parent 0aedad4 commit 9056367

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: Python/binary_search.py

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

0 commit comments

Comments
 (0)