python经典算法之折半查找
1、折半查找
def s2(li,key):
li.sort()
start=0
end=len(li)-1
while start<end:
mid=(start+end)//2
if li[mid]==key:
return mid
elif li[mid]<key:# 后半段
start=mid+1
else:
end=mid-1
return -1
li=[1,44,55,8,6,-5]
print(sorted(li))#[-5, 1, 6, 8, 44, 55]
print(s2(li,44))#4
2、使用递归的方式实现折半查找
li=[23,-8,26,-2,-6,-18,33]
li.sort()
# print(li)
n=len(li)
def fun(li,key,start,end):
if li[0]<=key<=li[-1]:
mid = (start+end)//2
if li[mid]==key:
return mid
if start>end:
return "查不到"
elif li[mid]<key:
return fun(li,key,mid+1,end)
else:
return fun(li,key,start,mid-1)
else:
return "查不到"
# print(fun(li,23,0,n-1))#4
# print(fun(li,3,0,n-1))#查不到
# print(fun(li,-100,0,n-1))#查不到