Skip to content

Commit 1caafe3

Browse files
Merge pull request #190 from Bhavdeepq/patch-1
Create binarysearch.py
2 parents 465b14f + 1801dc4 commit 1caafe3

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

binarysearch.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Python 3 program for recursive binary search.
2+
# Modifications needed for the older Python 2 are found in comments.
3+
4+
# Returns index of x in arr if present, else -1
5+
def binary_search(arr, low, high, x):
6+
7+
# Check base case
8+
if high >= low:
9+
10+
mid = (high + low) // 2
11+
12+
# If element is present at the middle itself
13+
if arr[mid] == x:
14+
return mid
15+
16+
# If element is smaller than mid, then it can only
17+
# be present in left subarray
18+
elif arr[mid] > x:
19+
return binary_search(arr, low, mid - 1, x)
20+
21+
# Else the element can only be present in right subarray
22+
else:
23+
return binary_search(arr, mid + 1, high, x)
24+
25+
else:
26+
# Element is not present in the array
27+
return -1
28+
29+
# Test array
30+
arr = [ 2, 3, 4, 10, 40 ]
31+
x = 10
32+
33+
# Function call
34+
result = binary_search(arr, 0, len(arr)-1, x)
35+
36+
if result != -1:
37+
print("Element is present at index", str(result))
38+
else:
39+
print("Element is not present in array")

0 commit comments

Comments
 (0)