递归二分法求数字位置,我试着用手推演了一遍程序,还是不明白为什么程序找不到“2”的位置?

程序如下:

#二分法判断数字是否存在在函数中
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 ("元素不在数组中")

运行结果如下:

img


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:
        return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 2
result = binary_search(arr,0,len(arr)-1, x)
if result != -1:
    print ("元素在数组中的索引为 %d" % result )
else:
    print ("元素不在数组中")