4.二分查找法查找列表中(列表中的元素非有序排列)所需要的某个元素(通过中位法获取对应的元素值,进行叠代查找比较,直至找到所需要的元素),输出要查找的元素xx存在,在下标为xx处,一共查找了xx次,如未找到,输出要查找的元素xx不存在,一共查找了xx次;(要查找的元素即为自己学号后两位,要求要有找到及未找到两种测试用例);
时间: 2023-06-27 20:07:39 浏览: 31
假设要查找的元素为target,列表为lst,可以使用以下代码实现二分查找:
```python
def binary_search(lst, target):
"""
在 lst 中查找 target,返回其下标和查找次数
如果未找到,返回 -1 和查找次数
"""
left, right = 0, len(lst) - 1
count = 0
while left <= right:
mid = (left + right) // 2
count += 1
if lst[mid] == target:
return mid, count
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1, count
```
对于要查找的元素,可以通过自己的学号后两位进行生成,例如:
```python
target = int('06') # 假设学号后两位为 06
```
然后可以构造一个无序列表 lst 进行测试,例如:
```python
lst = [3, 5, 2, 8, 1, 9, 7, 4, 6] # 无序列表
```
调用 binary_search 函数即可进行查找:
```python
idx, count = binary_search(lst, target)
if idx != -1:
print(f"要查找的元素 {target} 存在,在下标为 {idx} 处,一共查找了 {count} 次。")
else:
print(f"要查找的元素 {target} 不存在,一共查找了 {count} 次。")
```
如果要查找的元素存在于列表中,输出类似于以下的结果:
```
要查找的元素 6 存在,在下标为 8 处,一共查找了 3 次。
```
如果要查找的元素不存在于列表中,输出类似于以下的结果:
```
要查找的元素 6 不存在,一共查找了 4 次。
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)