1. 二分查找
二分查找对1~100乱序数字查找
l = list(range(1,101))
def bin_search(data_set,val):
low = 0
high = len(data_set) - 1
while low <= high:
mid = (low+high)//2
if data_set[mid] == val:
return mid
elif data_set[mid] < val:
low = mid + 1
else:
high = mid - 1
return
n = bin_search(l,11)
print(n) # 返回结果是: 10
当数列有序且从小到大时:
这个方法查找无序的结果将都是不存在
list = [1,2,3,4]
def Binary_search():
start = 0
end = len(list) - 1
num = 1
while start <= end:
mid = (start+end) // 2 # 先找中间值下标
if num == list[mid]:
print('该值对应的下标是:',mid)
return mid
elif num > list[mid]:
start = mid + 1
elif num < list[mid]:
end = mid - 1
print('不存在')
Binary_search()
2. 递归
- 递归条件
1、 自己调用自己
2、 有结束条件