给定一个有序序列,使用二分查找指定的值。(递归/非递归两种方法)
时间: 2024-02-06 11:09:47 浏览: 61
非递归方法:
```python
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
```
递归方法:
```python
def binary_search_recursive(arr, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
```
调用方法:
```python
arr = [1, 3, 5, 7, 9]
target = 5
# 调用非递归方法
result = binary_search(arr, target)
print(result)
# 调用递归方法
result = binary_search_recursive(arr, target, 0, len(arr) - 1)
print(result)
```
输出:
```
2
2
```
阅读全文