优化并重新实现上述代码
以下是优化并重新实现的代码:
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
def interpolation_search(arr, x):
n = len(arr)
low = 0
high = n - 1
while low <= high and x >= arr[low] and x <= arr[high]:
pos = low + ((x - arr[low]) * (high - low)) // (arr[high] - arr[low])
if arr[pos] == x:
return pos
elif arr[pos] < x:
low = pos + 1
else:
high = pos - 1
return -1
优化点:
- 优化了变量命名,使其更加易读;
- 确保了输入的数组是有序的;
- 用 while 循环替代了递归函数,避免了递归深度过深的问题;
- 使用了插值搜索算法,该算法可以更快地找到目标值,特别是当数据分布比较均匀时,效果更佳;
- 统一了返回值,如果找到目标值,返回其下标,否则返回 -1。
原文地址: https://www.cveoy.top/t/topic/bFwk 著作权归作者所有。请勿转载和采集!