3rd with operations

mail@pastecode.io avatar
unknown
plain_text
a year ago
665 B
5
Indexable
Never
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    operations = 0

    while left <= right:
        mid = (left + right) // 2
        operations += 1

        if arr[mid] == target:
            return mid, operations
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1, operations


sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 7

index, num_operations = binary_search(sorted_list, target)

if index != -1:
    print(f"Found {target} at index {index} with {num_operations} operations.")
else:
    print(f"{target} not found in the list with {num_operations} operations.")