diff --git a/algorithms/search/binary_search.py b/algorithms/search/binary_search.py index 6b398764c..2a7c9bc3e 100644 --- a/algorithms/search/binary_search.py +++ b/algorithms/search/binary_search.py @@ -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 diff --git a/algorithms/search/first_occurrence.py b/algorithms/search/first_occurrence.py index 119ba4df2..9d9beaae1 100644 --- a/algorithms/search/first_occurrence.py +++ b/algorithms/search/first_occurrence.py @@ -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