1 Star 0 Fork 1

王其/托管

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
二分检索.py 931 Bytes
一键复制 编辑 原始数据 按行查看 历史
王其 提交于 2021-10-26 16:49 +08:00 . add 二分检索.py.
#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)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wang-qi3206/trusteeship.git
git@gitee.com:wang-qi3206/trusteeship.git
wang-qi3206
trusteeship
托管
master

搜索帮助