编写函数,要求实现二分查找算法,已知序列为:arr = [3, 6, 7, 10, 15, 30, 39, 45,60]。
时间: 2023-07-02 07:21:59 浏览: 66
好的,以下是实现该函数的代码:
```python
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
arr = [3, 6, 7, 10, 15, 30, 39, 45, 60]
target = 10
result = binary_search(arr, target)
if result != -1:
print(f"元素在序列中的索引为:{result}")
else:
print("元素不在序列中")
```
函数`binary_search()`实现了二分查找算法,使用了迭代的方式。函数接受两个参数:`arr`为已知序列,`target`为需要查找的目标元素。首先,将`low`赋值为0,`high`赋值为序列长度减1,每一次循环,计算`mid`的值,并判断`arr[mid]`与`target`的关系,如果相等,则返回`mid`。如果`arr[mid]`小于`target`,说明目标元素在`mid`的右侧,将`low`更新为`mid+1`。反之,将`high`更新为`mid-1`。如果整个循环结束后仍然没有找到目标元素,则返回-1。最后,根据返回值判断目标元素是否在序列中,并输出相应的结果。
相关推荐
![](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)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)