pythone二分查找
时间: 2023-11-20 19:55:15 浏览: 60
以下是两种Python实现二分查找算法的方法:
方法一:
```python
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
arr = [1, 3, 6, 9, 10, 20, 30]
x = 10
result = binary_search(arr, 0, len(arr) - 1, x)
if result != -1:
print("元素在数组中的索引为", str(result))
else:
print("元素不在数组中")
```
方法二:
```python
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
arr = [1, 3, 6, 9, 10, 20, 30]
x = 10
result = binary_search(arr, x)
if result != -1:
print("元素在数组中的索引为", str(result))
else:
print("元素不在数组中")
```
阅读全文