二进制搜索问题没有给出预期的结果。不确定是什么导致了这个问题?

Binary search problem is not giving desired result. Not sure what is causing the issue?

这是我的代码:

尝试使用古老的二进制搜索算法从列表中搜索元素,

def binary_search(l, low, high, val):
    while low <= high:
        mid = (high + low) // 2
        #print(mid)
        if l[mid] > val:
            high = mid - 1
        elif l[mid] < val:
            low = mid + 1
        else:
            return mid
    return -1
        


arr = [1,24,5,3]
result = binary_search(arr, 0,(len(arr)-1), 5)

if result == -1:
    print(" Not present")
else:
    print("given number present at index", result)

输出为:“不存在”

我无法解决缺少正确索引的问题,为什么不为给定的 arr 重新调整索引 = 2。请帮忙。

在二进制搜索中数组应该排序。

试试 arr = [1,3,5,24]