二分法的两种实现(循环、递归)

li=[i for i in range(10000000)]
s=23000
def compare(start=0,end=len(li),now=len(li)//2):
if li[start]<s<li[now]:
end = now
now=(now+start)//2
start=start
elif li[now]<s<li[end]:
start=now
now = (now+end) // 2
end=end
elif s==li[start]:
return start
elif s==li[now]:
return now
elif s==li[end]:
return end
return compare(start,end,now)
print(compare())
li=[i for i in range(100)]
s=23
start=0
end=100
now=50
while 1 :
if li[start]<s<li[now]:
end = now
now=(now+start)//2
start=start
elif li[now]<s<li[end]:
start=now
now = (now+end) // 2
end=end
elif s==li[start]:
m= start
break
elif s==li[now]:
m=now
break
elif s==li[end]:
m= end
break
print(m)

猜你喜欢

转载自www.cnblogs.com/diracy/p/13371432.html
今日推荐