0

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.

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

You may as well simply use integer division: mid = (low+high)//2
And (low+high)/2 will always return a float, e.g. 4/2 returns 2.0 not 2.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.