(See the Complexity handout for the analysis of Binary Search)
def find_i_binary(L, e):
'''Returns the index of e in L, or None if e is not in L
Arguments:
L -- a sorted list of ints
e -- int
'''
low = 0
high = len(L) - 1
while high-low >= 2:
mid = (low+high)//2
if L[mid] > e:
high = mid - 1
elif L[mid] < e:
low = mid + 1
else:
return mid
if L[low] == e:
return low
elif L[high] == e:
return high
else:
return None
So, how does Binary Search compare to our previous attempt (called Linear Search)?
Suppose that one iteration of Binary Search runs $c_1$ ms, and one iteration of Linear Search runs $c_2$ ms. $c_1$ and $c_2$ are quite equal, but are pretty close.
For $n=1,000,000$, Binary Search will take, in the worst case, about $c_1\times \log_2 (1,000,000) = 20c_1$ ms. Linear Search will take $1,000,000 \times c_2$ ms. A big difference!
Of course, that's all assuming that the list is sorted. But if we need to perform multiple look-ups, it's worth it to sort the list the once, and then be able to use the much faster Binary Search.