raptor生成随机数折半查找
时间: 2024-01-02 12:23:07 浏览: 115
折半查找算法
折半查找是一种高效的查找算法,可以在有序数组中快速定位目标元素的位置。下面是使用Raptor生成随机数并进行折半查找的示例代码:
```python
import random
# 生成随机数
random_numbers = []
for i in range(10):
random_numbers.append(random.randint(1, 100))
print("随机数列表:", random_numbers)
# 对随机数列表进行排序
random_numbers.sort()
print("排序后的随机数列表:", random_numbers)
# 折半查找
target = random_numbers[random.randint(0, 9)]
low = 0
high = len(random_numbers) - 1
found = False
while low <= high:
mid = (low + high) // 2
if random_numbers[mid] == target:
found = True
break
elif random_numbers[mid] < target:
low = mid + 1
else:
high = mid - 1
if found:
print("目标元素", target, "在随机数列表中的位置为", mid)
else:
print("目标元素", target, "不在随机数列表中")
```
阅读全文