'''二分法查找
有序列表
掐头去尾取中间
查找列表中xx在不在列表中,在,则返回索引值'''
#lst = [1, 4, 6, 8, 9, 21, 23, 26, 35, 48, 49, 54, 67, 89, 99] #使用in判断,不使用二分法#n = 49#for i, v in enumerate(lst):#if v == n:#print("找到了,索引为%d" % i)#break#else:#print("没找到.")
'''二分查找'''
#lst = [1, 4, 6, 8, 9, 21, 23, 26, 35, 48, 49, 54, 67, 89, 99]#n = 49#left = 0#right = len(lst) - 1#while left <= right:#mid = (left + right) // 2#if n > lst[mid]:#left = mid + 1#elif n < lst[mid]:#right = mid - 1#else:#print("找到了,索引为:%d" % mid)#break#else:#print("没找到.")
'''使用递归调用完成二分法查找'''lst= [1, 4, 6, 8, 9, 21, 23, 26, 35, 48, 49, 54, 67, 89, 99]
n= 49
defbinarySearch(lst, n, left, right):if left <=right:
mid= (left + right)//2
if n
right= mid - 1
elif n >lst[mid]:
left= mid + 1
else:return "找到了,索引为:%d" %midreturnbinarySearch(lst, n, left, right)else:print("没找到.")return -1ret= binarySearch(lst, n, 0, len(lst)-1)print(ret)