Your described problem is that the algorithm you're using is intended to have upp
as the exclusive upper bound; by initializing it to len(list)-1
, you can't find the uppermost index at all. Change upp = len(list)-1
to upp = len(list)
and the code "works" (it just doesn't do anything useful).
Your other problems are:
num = list.index(int(input('Enter number: ')))
is getting you the index directly, with O(n)
search under the hood, eliminating the benefit of binary searching. The rest of your code isn't even looking at your list
, you're just doing O(log n)
work to find a mid
equal to num
, when mid = num
would achieve the same result with no search involved (no additional search beyond what list.index
was doing anyway).
- You named your variable
list
, which means the list
constructor is unavailable; this is a bad idea (even if it doesn't break anything here).
- (Not an issue in the current code, but an issue trying to fix #1) Your code experiences an infinite loop when the value being searched for is not in the
list
(in your current code, the list.index
call handles that by raising an exception, but as noted, if you use list.index
, you gain no benefit from binary search at all).
For #1, you wanted to accept the input without a list.index
call:
num = int(input('Enter number: '))
then change each comparison between num
and mid
to compare num
and list[mid]
(or mylist[mid]
or whatever better name you use for the list
), so num
is always the value being searched for, mid
is the current index being searched, and list[mid]
is the value at that index. You also need to improve your search so it stops when the value you're searching for doesn't exist in the list
(left as exercise; there's thousands upon thousands of examples of hand-implemented binary search, in pseudocode and Python, out there), rather than looping forever.