Below is an example of a Python binary search function that searches for a target element in a sorted list and returns its index. If the target is not found, the function returns -1.
python
def binary_search(arr, target):
"""
Performs binary search on a sorted list.
Parameters:
arr (list): A sorted list of elements.
target: The element to search for in the list.
Returns:
int: The index of the target in the list if found, else -1.
"""
left = 0
right = 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__":
# Example sorted list
numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17]
target = 7
index = binary_search(numbers, target)
if index != -1:
print(f"Target {target} found at index {index}.")
else:
print(f"Target {target} not found in the list.")
How It Works:
Initialization:
The function starts by initializing two pointers, left and right, representing the current search bounds.
Loop Until the Search Space is Exhausted:
The while left <= right: loop continues until the search space is empty.
Finding the Midpoint:
The midpoint mid is calculated as the integer division of (left + right) // 2.
Comparison and Adjusting the Search Bounds:
If arr[mid] equals the target, the function returns mid.
If arr[mid] is less than the target, the search continues on the right half by updating left to mid + 1.
Otherwise, if arr[mid] is greater than the target, the search continues on the left half by updating right to mid - 1.
Return Statement:
If the loop ends without finding the target, the function returns -1.
This implementation works for any sorted list. If your list is not sorted, you would need to sort it first or use a different searching algorithm.