I am learning about Binary Search in python and I decided that I want to implement it in actual code instead of just theory, so I found some examples and wrote some code. This is the code that I have written:
listData = [45, 125, 133, 192, 212, 256, 281, 283, 311, 358, 418, 424, 451, 483, 503, 567, 597,
602, 628, 651, 652, 677, 643, 778, 800, 805, 823, 842, 930, 945]
def binarySearch(listData, value):
low = 0
high = len(listData)
while (low <= high):
mid = (low+high)/2
if (listData[mid] == value):
return mid
elif (listData[mid] < value):
low = mid + 1
else:
high = mid - 1
return -1
print(binarySearch(listData, 45))
When I run this I get an error, this is the error:
Traceback (most recent call last):
File "C:\Users\Bobby Singh\Desktop\binaryalgosearch.py", line 16, in <module>
print(binarySearch(listData, 45))
File "C:\Users\Bobby Singh\Desktop\binaryalgosearch.py", line 8, in binarySearch
if (listData[mid] == value):
TypeError: list indices must be integers or slices, not float
Can anyone help me with this? Sorry for the bad formatting.
Your high
index should be high = len(listData) - 1
since the highest index for a list is lenght - 1
Also, you need to round the mid
since it can give 0.5
for cases that are odd. so do mid = round((low+high)/2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.