'''
二分法查找(三分法,一次分掉2/3)
有序序列 提高效率
'''
'''
# 遍历查询,效率低
lst = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222, 333, 444, 555]
n = 95
for el in lst:
if el == n:
print('找到了')
break
else:
print('没找到')
'''
# 二分法查找,效率高 (核心:掐头去尾取中间,一次砍一半)
# 1.while循环二分法
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99]
n = 40
left = 0
right = len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] > n:
right = mid - 1
if lst[mid] < n:
left = mid + 1
if lst[mid] == n:
print('找到了')
break
else:
print('没找到')
# 2.递归二分法查找
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99]
n = 33
left = 0
right = len(lst) - 1
def func(n, left, right):
if left <= right: # 查找边界
mid = (left + right) // 2
if lst[mid] > n:
right = mid - 1
return func(n, left, right) # 下次递归入口也是当前递归返回值
if lst[mid] < n:
left = mid + 1
return func(n, left, right) # 下次递归入口也是当前递归返回值
if lst[mid] == n:
print('找到了这个数')
return mid # 返回这个数索引,终止递归
else:
print('没找到这个数')
return -1 # 返回-1可计算 None不能参与后续计算
uu = func(n, left, right)
print('索引位置在', uu)
'''
# 索引下标查找法:
查找速度最快,仅一次.但会占用些许内存,时间复杂度和空间复杂度最低
'''
lst = [1, 2, 5, 6, 11, 22, 33, 55, 564]
def func(n, lst): # 在列表中查找n,存在返回True,不存在返回False
lst_t = []
for i in range(n + max(lst)): # 为lst_t添加0得到[0,0,0,0,0,...,0]的索引列表 最大查询数
lst_t.append(0)
for el in lst:
lst_t[el] = 1
# print(lst_t)
# print(len(lst_t)) # 列表lst_t长度
# 查找一个数在不在列表lst里面需要判断lst_t索引位置是否为1
if lst_t[n] == 1:
print('数{}在列表中'.format(n))
return True
else:
print('没有找到这个数')
return False
a = func(564, lst)
print(a)