二分法查找python的实现

def BinSearch(ls, value):
"""
使用二分法查找时列表内的元素必须是已经排好序的
:param ls:
:param value:
:return:
"""
minValue = 0
maxValue = len(ls) - 1
 
if value in ls:
while True:
center = int((minValue + maxValue) / 2)
if ls[center] > value:
maxValue = center - 1
 
elif ls[center] < value:
minValue = center + 1
 
elif ls[center] == value:
print("元素的索引是%s" % center)
break
 
else:
print("没有找到元素 %s" % value)
 
 
if __name__ == "__main__":
# datas = range(1, 1000)
datas = [88, 55, 22, 11, 99, 66, 77]
datas.sort()
print(datas)
BinSearch(datas, 88)
 
posted @ 2018-01-13 15:38  晴天小猫  阅读(228)  评论(0编辑  收藏  举报