使用python写一个二分法迭代
时间: 2023-05-17 11:04:04 浏览: 99
Python编程实现二分法和牛顿迭代法求平方根代码
实现:
```python
def binary_search_iterative(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
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
result = binary_search_iterative(arr, target)
if result != -1:
print("元素在数组中的索引为", str(result))
else:
print("元素不在数组中")
```
输出:
```
元素在数组中的索引为 4
```
希望能够帮到您!
阅读全文