搜索
常见搜索方法:
- 顺序查找
- 二分法查找
- 二叉树查找
- 哈希查找
二分法查找
非递归实现
def binary_search(item, a_sorted):
index = len(a_sorted)//2
while 0 < index < len(a_sorted)-1:
if a_sorted[index] == item:
# return True
return index
elif item < a_sorted[index]:
index = index//2
else:
index = index + index//2
if a_sorted[index] == item:
# return True
return index
else:
return False
if __name__ == "__main__":
list_a = [3, 4, 5, 9]
print(binary_search(5, list_a))
print(binary_search(3, list_a))
print(binary_search(9, list_a))
print(binary_search(8, list_a))
递归实现
def binary_search(item, a_sorted):
if len(a_sorted) == 0:
return False
else:
index = len(a_sorted)//2
if a_sorted[index] == item:
return True
elif item > a_sorted[index]:
# 注意返回值!!!
# print(a_sorted[index+1:])
return binary_search(item, a_sorted[index+1:])
else:
# print(a_sorted[:index])
return binary_search(item, a_sorted[:index])
if __name__ == "__main__":
list_a = [3, 4, 5, 9]
print(binary_search(5, list_a))
print(binary_search(3, list_a))
print(binary_search(9, list_a))
print(binary_search(8, list_a))