Click boxes to reveal numbers. The list is sorted left to right, top to bottom.
Decide whether ? is in the list โ using as few clicks as possible.
Ask your teacher for the password once everyone's had a go.
Not quite โ try again.
Worst case: checks on this list.
Worst case: checks on this list.
The idea: a sorted list is a shortcut waiting to be used. Every time you check the middle of what's left, you throw away half the remaining boxes at once โ that's why the smart way barely grows even on a huge list, while checking one by one gets slower and slower.
This is exactly what you just did, written as a real program. Read it next to the steps above โ every line matches one of the steps.
def linear_search(numbers, target):
for index in range(len(numbers)):
if numbers[index] == target:
return index # found it!
return -1 # never found it
def binary_search(numbers, target):
low = 0
high = len(numbers) - 1
while low <= high:
middle = (low + high) // 2
if numbers[middle] == target:
return middle # found it!
elif numbers[middle] < target:
low = middle + 1 # forget the left half
else:
high = middle - 1 # forget the right half
return -1 # never found it