使用python编写一段二分查找
- User
使用python编写一段二分查找
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
使用python编写一段二分查找
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
这里是Python二分查找的实现,我提供两种版本:
def binary_search(arr, target):
"""
在有序数组中查找目标值
Args:
arr: 有序数组
target: 要查找的目标值
Returns:
如果找到返回索引,否则返回-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
# 测试代码
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 7
result = binary_search(arr, target)
if result != -1:
print(f"找到了!索引位置:{result}")
else:
print("未找到目标值")
def binary_search_recursive(arr, target, left=0, right=None):
"""
递归实现二分查找
"""
if right is None:
right = len(arr) - 1
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
# 测试
arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
result = binary_search_recursive(arr, 11)
print(f"递归版本结果:{result}")
def binary_search_enhanced(arr, target):
"""
增强版二分查找,包含更多边界情况处理
"""
if not arr:
return -1
left, right = 0, len(arr) - 1
while left <= right:
# 防止整数溢出的写法
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# 测试各种情况
test_cases = [
([1, 2, 3, 4, 5], 3), # 正常情况
([1], 1), # 单元素
([], 1), # 空数组
([1, 2, 3, 4, 5], 6), # 不存在的元素
([1, 2, 3, 4, 5], 1), # 第一个元素
([1, 2, 3, 4, 5], 5), # 最后一个元素
]
for arr, target in test_cases:
result = binary_search_enhanced(arr, target)
print(f"数组: {arr}, 查找: {target}, 结果: {result}")
关键点说明:
left + (right - left) // 2可以避免大数溢出这个算法特别适用于在大型有序数据集中快速查找元素。