程序如下:
#二分法判断数字是否存在在函数中
def binary_search(list_sort, l, h, target):
if l <= h :
mid = l + (h-l)//2
if list_sort[mid] < target:
return binary_search(list_sort, mid+1, h, target)
elif list_sort[mid] > target:
return binary_search(list_sort, l, mid-1, target)
else:
return mid
else:
False
arr = [ 2, 3, 4, 10, 40 ]
x = 2
result = binary_search(arr,0,len(arr)-1, x)
if result:
print ("元素在数组中的索引为 %d" % result )
else:
print ("元素不在数组中")
运行结果如下: