Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary Search (Python) #275

Open
qingquan-li opened this issue Oct 17, 2024 · 0 comments
Open

Binary Search (Python) #275

qingquan-li opened this issue Oct 17, 2024 · 0 comments

Comments

@qingquan-li
Copy link
Owner

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant