How can I implement a binary search algorithm in Python?

97 views

How can I implement a binary search algorithm in Python?

How can I implement a binary search algorithm in Python?

solveurit24@gmail.com Changed status to publish February 13, 2025
0

def binary_search(arr, target):
    left = 0
    right = len(arr) - 1

    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

# Example usage:
arr = [2, 4, 6, 8, 10]
target = 6
index = binary_search(arr, target)
print(f"Element found at index {index}")  # Output: Element found at index 2

Here’s an implementation of binary search:

solveurit24@gmail.com Changed status to publish February 13, 2025
0