完成无序查找和有序查找,输出查找成功或不成功,及对应的查找次数
时间: 2024-06-14 11:05:14 浏览: 11
以下是无序查找和有序查找的示例代码:
1. 无序查找:
```python
def unordered_search(arr, target):
count = 0
for i in range(len(arr)):
count += 1
if arr[i] == target:
return f"查找成功,查找次数:{count}"
return "查找不成功"
arr = [5, 2, 8, 3, 9, 1]
target = 8
print(unordered_search(arr, target)) # 输出:查找成功,查找次数:3
```
2. 有序查找(折半查找):
```python
def binary_search(arr, target):
count = 0
low = 0
high = len(arr) - 1
while low <= high:
count += 1
mid = (low + high) // 2
if arr[mid] == target:
return f"查找成功,查找次数:{count}"
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return "查找不成功"
arr = [1, 2, 3, 5, 8, 9]
target = 8
print(binary_search(arr, target)) # 输出:查找成功,查找次数:3
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ZIP](https://img-home.csdnimg.cn/images/20210720083646.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)