The core problem is that this is not a correctly written Binary Search (see the algorithm there).
There is no need of index(target)
to find the solution; a binary search is O(lg n)
and so the very presence of index-of, being O(n)
, violates this! As written, the entire "binary search" function could be replaced as list1.index(value)
as it is "finding" the value index simply to "find" the value index.
The code is also slicing the lists which is not needed1; simply move the upper/lower indices to "hone in" on the value. The index of the found value is where the upper and lower bounds eventually meet.
Also, make sure that list1
is really a list such that the item access is O(1)
.
(And int
is not needed with //
.)
1 I believe that the complexity is still O(lg n)
with the slice, but it is a non-idiomatic binary search and adds additional overhead of creating new lists and copying the relevant items. It also doesn't allow the correct generation of the found item's index - at least without similar variable maintenance as found in a traditional implementation.