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.")
- Binary Search Function:
binary_searchtakes a sorted listarrand atargetelement to search for.leftandrightpointers are initialized to the start and end of the list, respectively.- A
whileloop runs as long asleftis less than or equal toright. midis 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
leftpointer is moved tomid + 1. - If the middle element is greater than the target, the
rightpointer is moved tomid - 1. - If the target element is not found,
-1is returned.
- Example Usage:
- A sorted list
arris defined. - A target element
targetis defined. binary_searchis called witharrandtarget.- The result is printed, indicating whether the element was found and its index.
- A sorted list
You can run this script to see how binary search works in finding the index of the target element in a sorted list.