首页 > 代码库 > Python实现二分法查找

Python实现二分法查找

#二分查找

def search_val(data_list, val):
    left = 0
    right = len(data_list) - 1
    while left <= right:
        mid = (left + right) // 2
        if data_list[mid] == val:
            return mid
        elif data_list[mid] > val:
            right = mid - 1
        else:
            left = mid + 1
    return -1

data_list = [1, 2, 3, 5, 6, 7, 8, 9, 12, 34, 45, 56, 66]
val = 3

print(search_val(data_list, val))

 

Python实现二分法查找