给定一个有序序列,使用二分查找指定的值。(递归/非递归两种方法)
时间: 2024-02-06 13:09:47 浏览: 57
非递归实现:
```python
def binary_search(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:
left = mid + 1
else:
right = mid - 1
return -1
```
递归实现:
```python
def binary_search(arr, target, left=0, right=None):
if right is None:
right = len(arr) - 1
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid + 1, right)
else:
return binary_search(arr, target, left, mid - 1)
```
这两种实现方式都是基于有序序列的,时间复杂度为 $O(\log n)$。
阅读全文