二分查找
二分查找要求数组必须有序,代码比较容易理解
如下:
# coding: utf-8
# non-recurse
# 迭代版
def binary_search(alist, aitem):
n = len(alist)
start = 0
end = n - 1
while start <= end:
mid = (start + end) // 2
if alist[mid] == aitem:
return True
elif aitem < alist[mid]:
end = mid - 1
else:
start = mid + 1
return False
# recurse
# 递归版
def binary_search_recurse(alist, aitem):
n = len(alist)
if n == 0:
return False
mid = n // 2
if aitem == alist[mid]:
return True
elif aitem < alist[mid]:
return binary_search_recurse(alist[:mid], aitem)
else:
return binary_search_recurse(alist[mid + 1:], aitem)
if __name__ == "__main__":
arr1 = [0, 1, 3, 5, 7, 8]
item = 3
print
print(binary_search(arr1, item))
# print(binary_search_recurse(arr1, item))