Skip to content

Commit b65550e

Browse files
authored
Create Binary Search
Binary Search in Python using recursion
1 parent 229f8d6 commit b65550e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Binary Search

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Returns index of x in arr if present, else -1
2+
3+
def binary_search(arr, low, high, x):
4+
5+
if high >= low:
6+
mid = (high + low) // 2
7+
8+
9+
10+
# If element is present at the middle itself
11+
12+
if arr[mid] == x:
13+
14+
return mid
15+
16+
17+
18+
# If element is smaller than mid, then it can only
19+
20+
# be present in left subarray
21+
22+
elif arr[mid] > x:
23+
24+
return binary_search(arr, low, mid - 1, x)
25+
26+
27+
28+
# Else the element can only be present in right subarray
29+
30+
else:
31+
32+
return binary_search(arr, mid + 1, high, x)
33+
34+
35+
36+
else:
37+
38+
# Element is not present in the array
39+
40+
return -1
41+
42+
43+
44+
arr = [ 2, 3, 4, 10, 40 ]
45+
46+
x = 10
47+
result = binary_search(arr, 0, len(arr)-1, x)
48+
if result != -1:
49+
50+
print("Element is present at index", str(result))
51+
52+
else:
53+
54+
print("Element is not present

0 commit comments

Comments
 (0)