二分查找
在所给的序列中查找到目的元素。data=[1,2,5,8,12,14,16,19,20,25,26,35,37,40]
data = [1, 2, 5, 8, 12, 14, 16, 19, 20, 25, 26, 35, 37, 40]
def binary_search(dataset,x):
if len(dataset) > 1: # 列表长度大于1
mid = int(len(dataset)/2)
if dataset[mid] == x:
print(x, '已找到')
return
elif dataset[mid] > x: # 待查找元素在中位数的左边
binary_search(dataset[0:mid], x)
else: # 待查找元素在中位数的右边
binary_search(dataset[mid+1:], x)
else: # 列表中只有一个元素
if dataset[0] == x:
print(x, '已找到')
return x
else:
print('不存在', x)
find_num = int(input("输入要查找的数:"))
binary_search(data, find_num)