From the book "Natoku! Algorithm" For memorandum
def binary_search(list, item):
low = 0 #Track the search part of the list using low and high
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
guess = list[mid] #Examine the element in the middle
if guess == item: #Detect item
return mid #If the answer is correct, mid(index)return it
if guess > item: #The number I guessed was too big
high = mid -1
else: #Was too small
low = mid + 1
return None #If you can't find it, None
my_list = [1,3,5,7,9]
print binary_search(my_list, 3) #The answer is 3
2222222 # log2(100) = 7 log2 (100) is how many times 2 should be multiplied to get 100 The answer is 7
It turned out that the number of searches can be obtained by logarithmic conversion.
Recommended Posts