用python编写程序:二分查找法查找序列类型中所需要的元素(通过中位法获取对应的元素值,进行叠代查找比较,直至找到所需要的元素,输出要查找的元素xx存在,在下标为xx处,一共查找了xx次,如未找到,输出要查找的元素xx不存在,一共查找了xx次;
时间: 2023-11-11 14:07:41 浏览: 83
好的,以下是使用二分查找法查找序列类型中所需要的元素的Python程序:
```python
def binary_search(arr, target):
"""
二分查找法查找序列类型中所需要的元素
:param arr: 待查找的有序序列
:param target: 目标元素
:return: 如果找到,返回目标元素的索引;否则,返回-1
"""
left = 0
right = len(arr) - 1
count = 0
while left <= right:
mid = (left + right) // 2
count += 1
if arr[mid] == target:
return mid, count
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1, count
if __name__ == '__main__':
nums = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 13
index, count = binary_search(nums, target)
if index != -1:
print(f"要查找的元素{target}存在,在下标为{index}处,一共查找了{count}次")
else:
print(f"要查找的元素{target}不存在,一共查找了{count}次")
```
运行结果如下:
```
要查找的元素13存在,在下标为6处,一共查找了3次
```
其中,`binary_search` 函数实现了二分查找法的核心逻辑。在函数中,我们通过初始化左右边界值 `left` 和 `right`,循环进行中位数的计算,然后根据当前中位数和目标元素的大小关系,缩小查找范围,直至找到目标元素或者左右边界值相遇。
在主函数中,我们定义了一个有序序列 `nums` 和要查找的目标元素 `target`,然后调用 `binary_search` 函数进行查找,并根据查找结果进行输出。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)