二分法查找:从有序集合a中找到具体值b所在位置
a = [1,2,3,4,5,6,7,8,9]
b = 2
def ef1(a,b):
a_len = len(a)
begin = 0
end = a_len
index = int(a_len/2)
deep = 0
while True:
deep = deep+1
print(deep,end='')
if b==a[index]:
print('\nfind b on index={},b={},find={}'.format(index,b,a[index]))
break
elif a[index] > b:
end = index-1
else:
begin = index+1
index = int((end+begin)/2)
a = range(100)
for b in range(100) :
ef1(a,b)
>>>
123456
find b on index=0,b=0,find=0
...
1
find b on index=50,b=50,find=50
...
123456
find b on index=99,b=99,find=99
def erf(a,b,begin,end,deep=0):
deep = deep+1
print(deep,end='')
index = int((begin+end)/2)
if b==a[index]:
print('\nfind b on index={},b={},find={}'.format(index,b,a[index]))
elif a[index] > b:
end = index-1
erf(a,b,begin,end,deep)
else:
begin = index+1
erf(a,b,begin,end,deep)
a = range(100)
begin = 0
end = len(a)
for b in a:
erf(a,b,begin,end)