1. 程式人生 > >遞歸:python 實現2分查找

遞歸:python 實現2分查找

search n) arch pytho elif range int 查找 ear

2分查找

def data_search(n,m):
mid = int(len(n)/2)
if len(n)>=1:
if n[mid]>m:
print(‘要尋找的數字在%s左邊‘%n[mid])
data_search(n[:mid], m)
elif n[mid]<m:
print(‘要尋找的數字在%s右邊‘%n[mid])
data_search(n[mid:], m)
else:
print(‘找到該數字‘)
else:
print(‘找不到該數字‘)


if __name__ == ‘__main__‘:
data = list(range(1,700))
data_search(data,300)

遞歸:python 實現2分查找