插值查找python的伪代码
时间: 2023-11-17 20:02:19 浏览: 41
以下是使用插值查找算法在Python中的伪代码:
```
#实现插值查找算法,ele 表示要查找的目标元素,[begin,end] 指定查找区域
def interpolation_search(arr,begin,end,ele):
#如果[begin,end] 不存在,返回 -1
if begin > end:
return -1
if begin == end:
if arr[begin] == ele:
return begin
return -1
#找到中间元素所在的位置
mid = int(begin + ((end - begin) / (arr[end] - arr[begin]) * (ele - arr[begin])))
#递归的出口
if ele == arr[mid]:
return mid
#比较 ele 和 arr[mid] 的值,缩小 ele 可能存在的区域
if ele < arr[mid]:
return interpolation_search(arr,begin,mid-1,ele)
else:
return interpolation_search(arr,mid+1,end,ele)
arr = [1,2,3,4,5,6,7,8,9,10]
#输出元素 2 所在位置的下标
add = interpolation_search(arr, 0, 9, 2);
if add != -1:
print(add)
else:
print("查找失败")
```
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)