二分算法的定义不在多说了,百度一下就知道(支持国产
)
import sys
source = [1,2,3,4,5,6,7,8,9,10] #must be in order
des = int(sys.argv[1])
low = 0
high = len(source) - 1
targetIndex = -1
print "des=",des
while low <= high:
middle = (low + high)/2
if des == source[middle]:
targetIndex = middle
break
elif des < source[middle]:
high = middle -1
print "middle element[index=",middle,",value=",source[middle],"] is bigger than des, continue search from[",low,"to",high,"]"
else:
low = middle + 1
print "middle element[index=",middle,",value=",source[middle],"] is smaller than des, continue search from[",low,"to",high,"]"
print "search complete, target element's index in source list is ",targetIndex
运行结果如下: