问题:在排序数组中高效搜索特定值是计算机科学中的一个常见问题。当数据分布不均匀时,二进制搜索等传统搜索算法可能无法达到最佳效果。我们需要一种能适应数据分布的算法。
解决方案: 插值搜索算法可以高效地搜索排序数组中的目标值。
以下是插值搜索算法的 Python 代码:
def interpolation_search(arr, target):
low, high = 0, len (arr) - 1
while low <= high and arr [low] <= target <= arr[high]:
if low == high:
return low if arr[low] == target else -1
pos = low + (target - arr[low]) * (high - low) // (arr[high] - arr [low])
if arr[pos] == target:
return pos
low = pos + 1 if arr[pos] < target else low
high = pos - 1 if arr[pos] > target else high
return -1
# Example Usage:
arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
target = 12
result = interpolation_search (arr, target)
if result != -1:
print (f"Element {target} found at index {result}")
else:
print (f"Element {target} not found in the array")
# Element 12 found at index 5
