文章目录
- 一. 二分查找
- 二. 代码实现一:使用递归
- 三. 代码实现二:非递归
一. 二分查找
二. 代码实现一:使用递归
def binary_search(alist, item):"""二分查找:使用递归"""n = len(alist)if n > 0:mid = n // 2if alist[mid] == item:return Trueelif item < alist[mid]:return binary_search(alist[:mid],item)else:return binary_search(alist[mid+1:],item)return Falseif __name__ == '__main__':li = [17,20,26,31,44,54,55,77,93]print(binary_search(li,55))print(binary_search(li,100))
三. 代码实现二:非递归
def binary_search_2(alist,item):"""二分查找:非递归"""n = len(alist)first = 0last = n-1while first <= last:mid = (first + last)//2if alist[mid] == item:return Trueelif item < alist[mid]:last = mid-1else:first = mid + 1return Falseif __name__ == '__main__':li = [17,20,26,31,44,54,55,77,93]print(binary_search_2(li,55))print(binary_search_2(li,100))