我是007 发表于 2017-5-1 07:33:02

python实现二分查找算法

  二分算法的定义不在多说了,百度一下就知道(支持国产)

import sys
source = #must be in order
des = int(sys.argv)
low = 0
high = len(source) - 1
targetIndex = -1
print "des=",des
while low <= high:
middle = (low + high)/2
if des == source:
targetIndex = middle
break
elif des < source:
high = middle -1
print "middle element,"] is bigger than des, continue search from[",low,"to",high,"]"
else:
low = middle + 1
print "middle element,"] is smaller than des, continue search from[",low,"to",high,"]"
print "search complete, target element's index in source list is ",targetIndex
  运行结果如下:
页: [1]
查看完整版本: python实现二分查找算法