How to Implement a Simple Binary Search Algorithm in Python

def binary_search(arr, target):
    low, high = 0, len(arr) - 1

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

    return -1

sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target_value = 6
result_index = binary_search(sorted_list, target_value)
print(f"Sorted List: {sorted_list}\nIndex of {target_value}: {result_index}")

Output:

Sorted List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Index of 6: 5

Leave a Comment

Your email address will not be published.