def binary_search(arr, key):
store_middle = 0
length = len(arr)
while store_middle <= length:
middle = (store_middle length) // 2
if arr[middle] == key: # throws list index out of range
print(f"Key: {key} is in the {middle} list index")
break
else:
if arr[middle] < key:
store_middle = middle 1
else:
length = middle - 1
return key
binary_search([2, 3, 5, 8, 14, 12], 14)
The function searches for the 'key' in the given array. When I provide the 'key' larger than 12 the function throws 'list index out of range'. I can't figure out the reason why, it doesn't make any sense why this is happening.
CodePudding user response:
while store_middle <= length
When store_middle = length
, you'll cause the error, since the last valid index has value len(arr)-1
. Just change it to
while store_middle < length
CodePudding user response:
A couple of things:
When
store_middle
andlength
both equal tolen(arr)
,mid
will be out of bounds according to the existing logic.To fix this, either set
length = len(arr) - 1
or update the loop condition to bewhile store_middle < length
. The former is usually preferred as it can be easily updated to find a "lower bound".Binary search works on a sorted container. If you're trying to find something in this array
[2, 3, 5, 8, 14, 12]
, binary search won't work.