随机输入(或随机产生)30个数,采用顺序、折半查找在(1)中排好序的数据中完成查找任务
时间: 2023-06-25 14:07:57 浏览: 79
好的,以下是一个示例代码,其中使用了Python的random模块来生成随机数,以及顺序查找和折半查找算法来查找数据:
```python
import random
# 生成30个随机数
data = [random.randint(1, 100) for i in range(30)]
# 排序
data.sort()
# 输出排序后的数据
print("排序后的数据:", data)
# 顺序查找
def sequential_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i
return -1
# 折半查找
def binary_search(data, target):
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
if data[mid] == target:
return mid
elif data[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# 随机选择一个数作为要查找的目标值
target = random.choice(data)
# 在排序后的数据中进行顺序查找
index = sequential_search(data, target)
if index == -1:
print("{} 不在数据中".format(target))
else:
print("{} 在数据中,索引为 {}".format(target, index))
# 在排序后的数据中进行折半查找
index = binary_search(data, target)
if index == -1:
print("{} 不在数据中".format(target))
else:
print("{} 在数据中,索引为 {}".format(target, index))
```
运行结果可能如下:
```
排序后的数据: [1, 9, 11, 14, 17, 20, 21, 21, 22, 28, 33, 34, 34, 45, 49, 50, 55, 56, 59, 60, 63, 65, 68, 69, 73, 74, 76, 79, 80, 94]
60 在数据中,索引为 19
60 在数据中,索引为 19
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)