二进制搜索(Binary Search)是一种在有序数组中查找特定元素的搜索算法。其基本思想是通过每次比较数组中间元素与目标值,逐步缩小搜索范围,直到找到目标值或确定目标值不存在。
mid = (low + high) / 2
。def binary_search(arr, target, low, high):
if high >= low:
mid = (high + low) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search(arr, target, low, mid - 1)
else:
return binary_search(arr, target, mid + 1, high)
else:
return -1
# 示例数组
arr = [2, 3, 4, 10, 40]
target = 10
result = binary_search(arr, target, 0, len(arr) - 1)
if result != -1:
print("元素在索引 %d 处找到" % result)
else:
print("元素不在数组中")
def binary_search(arr, target):
low, high = 0, 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 = [2, 3, 4, 10, 40]
target = 10
result = binary_search(arr, target)
if result != -1:
print("元素在索引 %d 处找到" % result)
else:
print("元素不在数组中")
-1
。通过以上信息,你应该对二进制搜索有了全面的了解,并且能够解决相关的问题。
领取专属 10元无门槛券
手把手带您无忧上云