Skip to content

Commit a336ee8

Browse files
authored
Update binary_search.py (#902)
* Update binary_search.py * Update first_occurrence.py
1 parent c0e5404 commit a336ee8

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

algorithms/search/binary_search.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,18 +34,19 @@ def binary_search(array, query):
3434
high = mid - 1
3535
return None
3636

37+
#In this below function we are passing array, it's first index , last index and value to be searched
3738
def binary_search_recur(array, low, high, val):
3839
"""
3940
Worst-case Complexity: O(log(n))
4041
4142
reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
4243
"""
43-
44-
if low > high: # error case
44+
#Here in Logic section first we are checking if low is greater than high which means its an error condition because low index should not move ahead of high index
45+
if low > high:
4546
return -1
46-
mid = (low + high) // 2
47-
if val < array[mid]:
48-
return binary_search_recur(array, low, mid - 1, val)
47+
mid = low + (high-low)//2 #This mid will not break integer range
48+
if val < array[mid]:
49+
return binary_search_recur(array, low, mid - 1, val) #Go search in the left subarray
4950
if val > array[mid]:
50-
return binary_search_recur(array, mid + 1, high, val)
51+
return binary_search_recur(array, mid + 1, high, val) #Go search in the right subarray
5152
return mid

algorithms/search/first_occurrence.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def first_occurrence(array, query):
1111

1212
low, high = 0, len(array) - 1
1313
while low <= high:
14-
mid = (low + high) // 2
14+
mid = low + (high-low)//2 #Now mid will be ininteger range
1515
#print("lo: ", lo, " hi: ", hi, " mid: ", mid)
1616
if low == high:
1717
break

0 commit comments

Comments
 (0)