I am trying to implement binary search with the following function:
def buggy_binary_search(input, key):
low = 0
high = len(input)-1
mid = (low + high)/2
while low <= high:
if input[mid] == key:
return mid
if input[mid] > key:
high = mid - 1
else:
low = mid
return -1
The above function when run, gets into a infinite loop. How can I correct that?
low = mid + 1
also in theelse
condition, apart from updatingmid
in the while loop. – Verdibisect
module that implements binary search. I suggest you to read its source code. The module implements both "right" binary search and "left" binary search, i.e. searches that always return the rightmost or leftmost occurrence of the element. (it's underLib/bisect.py
in the python sources). – Zonnya