Safwan Abrar
Safwan Abrar

Reputation: 127

Python: Binary Search Code not working as intended

Here is my code:

array = [14, 17, 25, 26, 56, 59, 78, 90, 99, 104]
low = 1
high = len(array)
found = False
item = int(input('Henlo, giv number pls :)\n'))

while high >= low and found == False:
    middle = int((low + high) / 2)
    if item < array[middle]:
        high = middle - 1
    elif item == array[middle]:
        found = True
    else:
        low = middle + 1

if found == True:
    print('Found')
else:
    print('Not Found')

It works, but whenever I try to search for the first item in the array (whether it's 14 or any other number as long as the whole array is in ascending order), it returns 'Not Found.' It works for all the other numbers, and if I put a number in that isn't in the array, it displays 'Not Found' like its supposed to, except when the number is larger than the last number in the array, for example 105, then it give list index out of range error, a solution to this problem will also be helpful.

Thanks :)

Upvotes: 1

Views: 45

Answers (2)

ewan_jordan
ewan_jordan

Reputation: 76

This is actually a quick fix. Arrays are indexed starting at 0 instead of 1 so you just need to set low = 0 instead of 1 and change high = len(array) -1 because the length of the array counts starting from 1 and not 0; hence the - 1

Upvotes: 1

Mike67
Mike67

Reputation: 11342

You need to adjust your array limits.

array = [14, 17, 25, 26, 56, 59, 78, 90, 99, 104]
print(array)
low = 0  # minimum index in array
high = len(array)-1  # maximum index in array
found = False
item = int(input('Henlo, giv number pls :)\n'))

while high >= low and found == False:
    middle = int((low + high) / 2)
    if item < array[middle]:
        high = middle - 1
    elif item == array[middle]:
        found = True
    else:
        low = middle + 1

if found == True:
    print('Found')
else:
    print('Not Found')

Upvotes: 1

Related Questions