代码拉取完成,页面将自动刷新
#coding=utf-8
#二分检索并确定在哪个位置
def binary_search(list_: list, item):
n = len(list_)
if n < 1:
return False
left = 0
right = n - 1
mid = (left + right) // 2
if list_[mid] == item:
return mid
elif item < list_[mid]:
newList = list_[0:mid]
newResult=binary_search(newList,item)
if newResult is False:
return False
else:
return binary_search(newList, item)
elif item > list_[mid]:
newList = list_[mid+1:]
newResult=binary_search(newList,item)
if newResult is False:
return False
else:
return mid + binary_search(newList, item) + 1
if __name__ == '__main__':
list_ = [9, 11, 33, 36, 48, 52, 74, 87]
for item in [7,9,11,33,36,37,48,52,74,87,88,100]:
result = binary_search(list_, item)
print(result)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。