Aka: half-interval search, logarithmic search, binary chop
Efficient method to find an element assuming the list is sorted. This allows us to disregard half the list on each attempt, thus leading to a boost from linear to logarithmic time.
Pros | Cons |
---|---|
Most efficient general-purpose method to find an element | Requires the collection to be sorted |
def binary_search(target, sorted_list):
low, high = 0, len(sorted_list) - 1
while low <= high:
middle = low + int((high-low)/2)
if sorted_list[middle] == target:
return middle
elif sorted_list[middle] < target:
low = middle + 1
else:
high = middle - 1
return -1
def binary_search(target, sorted_list):
low, high = 0, len(sorted_list)
while low < high:
middle = low + int((high-low)/2)
if sorted_list[middle] == target:
return middle
elif sorted_list[middle] < target:
low = middle + 1
else:
high = middle
return -1
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
Performance | |
---|---|
Worst-case | O(log n) |
Average | O(log n) |
Best-case | O(1) |
Worst-case space | O(1) |