Skip to content

Commit

Permalink
Update binary_search.py (keon#902)
Browse files Browse the repository at this point in the history
* Update binary_search.py

* Update first_occurrence.py
  • Loading branch information
Anujeet23 authored Apr 4, 2023
1 parent c0e5404 commit a336ee8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
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

0 comments on commit a336ee8

Please sign in to comment.