Binary Search is a lot faster than linear search
#standard linear search
def linear_search(itemList, searchFor, startIndex=0, endIndex=None):
for item in itemList:
if item == searchFor:
return item
return None
#fast binary search
def binary_search(itemList, searchFor, startIndex=0, endIndex=None):
if endIndex is None:
endIndex = len(itemList)
while startIndex < endIndex:
mid = (startIndex + endIndex)//2
midval = itemList[mid]
if midval < searchFor:
startIndex = mid+1
elif midval > searchFor:
endIndex = mid
else:
return mid
return None
#test script
import random
import time
testList = [n for n in range(10000000)]
testValue = random.randint(0,10000000)
startTime = time.time()
print linear_search(testList, testValue)
elapse = time.time() - startTime
print "Linear [ms]", elapse * 1000.0
startTime = time.time()
print binary_search(testList, testValue)
elapse = time.time() - startTime
print "Binary [ms]", elapse * 1000.0
#console output
6757414
Linear [ms] 326.999902725
6757414
Binary [ms] 0.0
|