nickolasaperes / github-blog-rocketseat

0 stars 0 forks source link

Python Binary Search #2

Open nickolasaperes opened 3 months ago

nickolasaperes commented 3 months ago

Python Binary Search recursive

def binary_search(arr: List[int], low: int, high: int, x: int):
    if low > high:
        return None

    mid = (low + high) // 2
    guess = arr[mid]

    if guess == x:
        return mid

    if guess > x:
        return binary_search_recursive(arr, low, mid - 1, x)

    return binary_search_recursive(arr, mid + 1, high, x)

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6, 7, 8]
    print(binary_search(arr, 0, len(arr), 5))
nickolasaperes commented 3 months ago

comment