Python script to perform binary search

mahabub.devs3
Mahabubur Rahman
Published on Nov, 26 2024 1 min read 0 comments
image

Here's a simple Python script to perform a binary search on a sorted list:

def binary_search(arr, target):
    left, right = 0, 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 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 7

result = binary_search(arr, target)

if result != -1:
    print(f"Element found at index {result}")
else:
    print("Element not found in the array")

This script defines a binary_search function that takes a sorted list arr and a target value to find. It returns the index of the target if found, otherwise it returns -1. The example usage demonstrates how to call this function and handle the result.

Feel free to ask if you have any questions or need further assistance!

0 Comments