二分查找递归和非递归python完整代码
时间: 2023-11-09 14:00:15 浏览: 100
二分查找是一种常见的查找算法,可以在有序数组中快速查找目标元素。下面是二分查找的递归和非递归实现的Python代码:
递归实现:
```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, left, mid - 1)
else:
return binary_search_recursive(arr, target, mid + 1, right)
```
非递归实现:
```python
def binary_search_iterative(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
```
阅读全文