defbin_search_first(array,t):
n = len(array)
if n == 0 :return -1
l = 0;u = n-1
p = -1while l <= u:
m = (l+u)//2if array[m] == t:
p = m
if m>0and array[m-1]==t:
u = m-1else:breakelif array[m] < t:
l = m+1else:
u = m-1return p
deftest():import random
for i in range(2,100):
array = [random.randint(0,5) for k in range(100)]
array.sort()
t = random.randint(0,5)
print(t,bin_search_first(array,t),array.index(t))
test()
第3题:编写一个递归版本的二分搜索
defrecur_bin_search(array,t):defbin_search(l,u):if l>u:return -1
m = (l+u)//2if array[m]==t:return m
elif array[m]<t:return bin_search(m+1,u)
else:return bin_search(l,m-1)
return bin_search(0,len(array)-1)
deftest():import random
for i in range(2,100):
array = [k for k in range(100)]
t = random.randint(0,i-1)
print(t,recur_bin_search(array,t),array.index(t))
test()
deffind_segment(a,b,x,y):assert(len(a)==len(b))
n = len(a)
defline(m):return a[m]*x+b[m]
defbin_search(x,y):
l = 0;u = n-2
p = -1while l<=u:
m = (l+u)//2
print(m)
if line(m) > y and line(m+1) < y:
p = m;breakelif line(m) < y:
u = m-1elif line(m+1) > y:
l = m+1return p
return bin_search(x,y)
第二题:用来用二分搜索法返回所搜寻元素出现的第一个位置。def bin_search_first(array,t): n = len(array) if n == 0 :return -1 l = 0;u = n-1 p = -1 while l <= u: m = (l+u)//2 if array[m] == t: