Skip to content

Update binary_search.py #902

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions algorithms/search/binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,19 @@ def binary_search(array, query):
high = mid - 1
return None

#In this below function we are passing array, it's first index , last index and value to be searched
def binary_search_recur(array, low, high, val):
"""
Worst-case Complexity: O(log(n))

reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
"""

if low > high: # error case
#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
if low > high:
return -1
mid = (low + high) // 2
if val < array[mid]:
return binary_search_recur(array, low, mid - 1, val)
mid = low + (high-low)//2 #This mid will not break integer range
if val < array[mid]:
return binary_search_recur(array, low, mid - 1, val) #Go search in the left subarray
if val > array[mid]:
return binary_search_recur(array, mid + 1, high, val)
return binary_search_recur(array, mid + 1, high, val) #Go search in the right subarray
return mid
2 changes: 1 addition & 1 deletion algorithms/search/first_occurrence.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def first_occurrence(array, query):

low, high = 0, len(array) - 1
while low <= high:
mid = (low + high) // 2
mid = low + (high-low)//2 #Now mid will be ininteger range
#print("lo: ", lo, " hi: ", hi, " mid: ", mid)
if low == high:
break
Expand Down