Skip to content

Commit ecb2cfb

Browse files
authored
Merge pull request DeepNinja07x#71 from vidhichadha2507/patch-8
binary search
2 parents 28537df + bd9335c commit ecb2cfb

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Data Strucrures/binary search

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

0 commit comments

Comments
 (0)