python 实现二分查找的两种常见方式

import time

def binary_search_1(alist, item):
”’二分查找递归版本”’
n = len(alist)
# 递归的终止条件, 至少有一个元素
if n > 0:
mid = n // 2
if alist[mid] == item:
return True
# 左侧
elif item < alist[mid]:
return binary_search_1(alist[:mid], item)

    else:
        return binary_search_1(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]:
# 计算下一个循环中间值时用的就是此时mid -1 的下标来计算的,所以才要减一
last = mid - 1

    else:
        first = mid + 1

def main():
”’主函数”’
li = [17, 20, 31, 44, 54, 55, 77, 93, 226]
first_time = time.time()
binary_search_1(li, 55)
print(‘递归用时:’, time.time() - first_time)

secod_time = time.time()
binary_search_2(li, 55)
print('循环用时:', time.time() - secod_time)

if name == ‘main‘:
main()

你可能感兴趣的:(python,python算法基础,常见算法实现)