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_search
takes a sorted listarr
and atarget
element to search for.left
andright
pointers are initialized to the start and end of the list, respectively.- A
while
loop runs as long asleft
is less than or equal toright
. 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 tomid + 1
. - If the middle element is greater than the target, the
right
pointer is moved tomid - 1
. - If the target element is not found,
-1
is returned.
- Example Usage:
- A sorted list
arr
is defined. - A target element
target
is defined. binary_search
is called witharr
andtarget
.- 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.