Implement Binary Search in Python
Here is an example of a binary search algorithm written in Python:
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# 测试
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 5
result = binary_search(arr, target)
if result != -1:
print(f"目标元素 {target} 在数组中的索引位置为 {result}")
else:
print("目标元素不在数组中")
In this example, the binary_search function takes a sorted array arr and a target element target as parameters, and returns the index position of the target element in the array. If the target element is not in the array, it returns -1.