finding a needle (a number) in a haystack (a list)
def linearSearch(needle, haystack):
comparisons = 1
for element in haystack:
printNow(str(comparisons))
if element == needle:
return 0
comparisons += 1
return 0
def binarySearch(needle, haystack):
low = 1
high = len(haystack) - 1
comparisons = 1
while (low <= high):
middle = int((low+high)/2.0)
printNow(str(comparisons)+":Checking at: "+str(middle)+" low="+str(low)+" high="+str(high))
if haystack[middle]==needle:
return 1
if haystack[middle]<needle:
low = middle+1
if haystack[middle]>needle:
high = middle-1
comparisons += 1
return 0
Link to this Page