
Sue Evans & Travis Mayberry
if x in list:
# linearSearch() searches for the item in myList and returns
# the index of item in the list myList, or -1 if not found.
# Inputs: item, the item to search for
# myList, the list to search for item
# Output: the index where item was found or -1 if index was
# not in the list
def linearSearch(item, myList):
for index in range(len(myList)):
if myList[index] == item:
return index
return -1

# binarySearch() performs a binary search for an item in a list
# Inputs: list, the list to search
# item, the item to search for
# Output: the index of item in the list, or -1 if not found
def binarySearch(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) / 2
# if found return the index
if item == list[mid]:
return mid
# if item is in the 2nd half of the list
elif item > list[mid]:
low = mid + 1
# if item is in the 1st half of the list
else:
high = mid - 1
# item was not in list
return -1
| N
| log2(N) |
|---|---|
| 1 | 1 |
| 10 | 3 |
| 100 | 7 |
| 1,000 | 10 |
| 1,000,000 | 20 |
Keep in mind that a linear search of a list containing 1,000,000 items would require 1,000,000 accesses in the worst case.
So binary search which runs in log2(n) is amazingly fast!