Binary Search
def binarySearch(target, listOfValues):
beginning = 0
end = len(listOfValues)
found = False
while (! found and (beginning <= end)):
middle = (beginning + end) / 2
if (listOfValues[middle] == target):
found = True
print "Found it at location: ", middle
else:
if (target < listOfValues[middle]):
end = middle -1
else:
beginning = middle + 1
if (! found):
print "Item not found"
- If we count number of comparisons, what is the best case performance for this algorithm on a list of size n?
- If we count number of comparisons, what is the worst case performance for this algorithm on a list of size n?