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)