数据结构:实现二分查找的递归算法,要求,随机产生100个随机整数,使用选择排序法对其排序,然后用二分查找的递归
时间: 2024-03-14 11:46:12 浏览: 146
python二分查找算法的递归实现方法
5星 · 资源好评率100%
好的,以下是实现二分查找的递归算法的Python代码:
```python
import random
def selection_sort(numbers):
for i in range(len(numbers)):
min_index = i
for j in range(i+1, len(numbers)):
if numbers[j] < numbers[min_index]:
min_index = j
numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
def binary_search_recursion(numbers, left, right, target):
if left > right:
return False
mid = (left + right) // 2
if target == numbers[mid]:
return True
elif target < numbers[mid]:
return binary_search_recursion(numbers, left, mid-1, target)
else:
return binary_search_recursion(numbers, mid+1, right, target)
numbers = [random.randint(1, 1000) for i in range(100)]
selection_sort(numbers)
target = random.randint(1, 1000)
if binary_search_recursion(numbers, 0, len(numbers)-1, target):
print(f"{target} exists in the list.")
else:
print(f"{target} does not exist in the list.")
```
代码中使用了选择排序法将随机整数数组进行排序,然后使用二分查找的递归算法查找目标值是否存在于数组中。
阅读全文