给出折半查找的递归和非递归算法
时间: 2024-12-11 22:13:02 浏览: 11
非递归折半查找
折半查找也叫二分查找,是一种在有序数组中查找特定元素的搜索算法。以下是折半查找的递归和非递归版本:
**递归算法(Python):**
```python
def binary_search_recursive(arr, target, low, high):
if low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, high)
else:
return binary_search_recursive(arr, target, low, mid - 1)
else:
return -1 # 如果目标不在数组中,返回-1
# 使用方法
arr = [1, 3, 5, 7, 9]
target = 5
result = binary_search_recursive(arr, target, 0, len(arr) - 1)
```
**非递归算法(Python):**
```python
def binary_search_iterative(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 = [1, 3, 5, 7, 9]
target = 5
result = binary_search_iterative(arr, target)
```
阅读全文