2019.9.25-二分查找代码(递归和非递归方法)
Posted lishuide
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2019.9.25-二分查找代码(递归和非递归方法)相关的知识,希望对你有一定的参考价值。
# coding:utf-8
#[17, 20, 26, 31, 44, 54, 55, 77, 93]
#mid = n/2
#
#[17, 20, 26, 31]
#mid = n/2
def binary_search(alist, item):
"""二分查找,遞歸"""
n = len(alist)
if n > 0:
mid = n//2
if alist[mid] == item:
return True
elif item < alist[mid]:
return binary_search(alist[:mid], item)
else:
return binary_search(alist[mid+1:], item)
return False
def binary_search_2(alist, item):
"""二分查找,非遞歸"""
n = len(alist)
first = 0
last = n-1
while first <= last:
mid = (first + last)//2
if alist[mid] == item:
return True
elif item < alist[mid]:
last = mid -1
else:
first = mid + 1
return False
if __name__ == "__main__":
li = [17, 20, 26, 31, 44, 54, 55, 77, 93]
print(binary_search(li, 55))
print(binary_search(li, 100))
print(binary_search_2(li, 55))
print(binary_search_2(li, 100))
执行结果
以上是关于2019.9.25-二分查找代码(递归和非递归方法)的主要内容,如果未能解决你的问题,请参考以下文章