Skip to content

Commit ebed906

Browse files
authored
Update Binary_search.py
Iterative approach take time. And time complexity is high. Instead of using this approach we can use recursive approach.
1 parent 734feaf commit ebed906

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

Binary_search.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
# It returns location of x in given array arr
22
# if present, else returns -1
33
def binarySearch(arr, l, r, x):
4-
while l <= r:
5-
6-
mid = l + (r - l) / 2 #extracting the middle element from the array
7-
mid=int(mid) #it has to be integer
8-
9-
# Check if x is present at mid
4+
if l <= r:
5+
6+
mid = (l+r) // 2 #extracting the middle element from the array
7+
8+
# If element is present at the middle itself
109
if arr[mid] == x:
1110
return mid
12-
13-
# If x is greater, ignore left half
14-
elif arr[mid] < x:
15-
l = mid + 1 #l is initialised to the rightmost element of the middle so that the search could be started from there the next time
16-
17-
# If x is smaller, ignore right half
18-
elif x<arr[mid]:
19-
r = mid - 1 #r is initialised to the leftmost element of the middle so that the search goes till there only the next time
20-
11+
12+
# If element is smaller than mid, then it can only
13+
# be present in left subarray
14+
elif arr[mid] > x:
15+
return binary_search(arr, l, mid - 1, x)
16+
17+
# Else the element can only be present in right subarray
18+
else:
19+
return binary_search(arr, mid + 1, r, x)
20+
2121
# If we reach here, then the element was not present
2222
return -1
2323

0 commit comments

Comments
 (0)