二分查找
#-*- coding:utf-8-*- #查找列表中的一个元素,列表是排好序的; #普通方法说 def search(list,element): for i in range(0,len(list)): if list[i] == element: print("list[%d] is %d" % (i,element)) return i print "not found!" #二分法查找,要求列表是有序的才行 def search2(list,element): low = 0 high = len(list)-1 while low <= high: middle = (low+high)/2 if list[middle]>element: high = middle-1 elif list[middle] < element: low = middle+1 else: print("list[%d] is %d" % (middle,element)) return 1 print "not found!" if __name__ == "__main__": list = [1, 3, 5, 7, 8, 9, 12, 45, 68] element = 6 search2(list,element)