blog icon indicating copy to clipboard operation
blog copied to clipboard

Binary Search (Python)

Open qingquan-li opened this issue 4 months ago • 0 comments

def binary_search(lst: list, target_value: int) -> int:
    left_index: int = 0
    right_index: int = len(lst) - 1
    mid_index: int

    if target_value < lst[0] or target_value > lst[-1]:
        return -1

    # while target_value != lst[mid_index]:
    # if the target_value doesn't exist in the list -> bug
    while left_index <= right_index:
        mid_index = (left_index + right_index) // 2

        if target_value == lst[mid_index]:
            return mid_index
        elif target_value > lst[mid_index]:
            left_index = mid_index + 1
        else:
            right_index = mid_index - 1

    return -1


#      0  1  2  3  4  5   6
lst = [1, 3, 5, 7, 9, 11, 13]
target_index_1 = binary_search(lst, 7)
target_index_2 = binary_search(lst, 11)
target_index_3 = binary_search(lst, 8)
target_index_4 = binary_search(lst, 20)

print(target_index_1)  # 3
print(target_index_2)  # 5
print(target_index_3)  # -1
print(target_index_4)  # -1

qingquan-li avatar Oct 17 '24 02:10 qingquan-li