Binary search using Python

Here’s an example of how you can implement binary search in Python, along with an example of how to use it.

def binary_search(arr, target):
    """
    Perform binary search on a sorted array.

    Parameters:
    arr (list): A sorted list of elements to search.
    target: The element to search for in the list.

    Returns:
    int: The index of the target element if found, otherwise -1.
    """
    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:
if __name__ == "__main__":
    # Sorted list
    arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]

    # Element to search for
    target = 7

    # Perform binary search
    result = binary_search(arr, target)

    if result != -1:
        print(f"Element {target} found at index {result}.")
    else:
        print(f"Element {target} not found in the list.")
  1. Binary Search Function:
    • binary_search takes a sorted list arr and a target element to search for.
    • left and right pointers are initialized to the start and end of the list, respectively.
    • A while loop runs as long as left is less than or equal to right.
    • mid is calculated as the middle index.
    • If the middle element is equal to the target, its index is returned.
    • If the middle element is less than the target, the left pointer is moved to mid + 1.
    • If the middle element is greater than the target, the right pointer is moved to mid - 1.
    • If the target element is not found, -1 is returned.
  2. Example Usage:
    • A sorted list arr is defined.
    • A target element target is defined.
    • binary_search is called with arr and target.
    • The result is printed, indicating whether the element was found and its index.

You can run this script to see how binary search works in finding the index of the target element in a sorted list.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top