【问题描述】输入一批从小到大的整数,以回车结束,存入列表中。再输入一个要查找的数,输出此数在列表中的索引位置,如不存在则输出﹣1。用扫描法或者二分法都可以 【输入形式】 【输出形式】 【样例输入输出】 Enter a number (< Enter > to quit ):1 Enter a number (< Enter > to quit ):2 Enter a number (< Enter > to quit ):5 Enter a number (< Enter > to quit ):6 Enter a number (< Enter > to quit ):8 Enter a number (< Enter > to quit ):10 Enter a number (< Enter > to quit ): Enter a number searched :8 【样例说明】8在列表索引值为4的位置上【评分标准】Python语言
时间: 2024-02-12 08:07:12 浏览: 53
以下是Python代码实现,采用二分查找法:
```python
def binary_search(num_list, target):
left = 0
right = len(num_list) - 1
while left <= right:
mid = (left + right) // 2
if num_list[mid] == target:
return mid
elif num_list[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
num_list = []
while True:
num_str = input("Enter a number (<Enter> to quit):")
if num_str == "":
break
num_list.append(int(num_str))
target = int(input("Enter a number searched:"))
result = binary_search(num_list, target)
if result == -1:
print("Target not found")
else:
print("Target found at index", result)
```
输入样例:
```
Enter a number (<Enter> to quit):1
Enter a number (<Enter> to quit):2
Enter a number (<Enter> to quit):5
Enter a number (<Enter> to quit):6
Enter a number (<Enter> to quit):8
Enter a number (<Enter> to quit):10
Enter a number (<Enter> to quit):
Enter a number searched:8
```
输出样例:
```
Target found at index 4
```
阅读全文