用Python写二分查找
以下是Python实现的二分查找算法:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
# 测试数组
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# 在数组中查找元素
result = binary_search(arr, x)
if result != -1:
print("元素在数组中的索引为", str(result))
else:
print("元素不在数组中")
输出:
元素在数组中的索引为 3
该算法的时间复杂度为O(logn),其中n为数组的长度。
原文地址: https://www.cveoy.top/t/topic/9ZG 著作权归作者所有。请勿转载和采集!