输入一批从小到大的整数,以回车结束,存入列表中。再输入一个要查找的数,输出此数在列表中的索引位置,如不存在则输出-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 4 【样例说明】8在列表索引值为4的位置上
时间: 2024-02-12 13:05:42 浏览: 123
好的,我明白了。以下是 Python 的代码实现:
```python
lst = []
while True:
num = input("Enter a number (<Enter> to quit):")
if num == "":
break
lst.append(int(num))
search_num = int(input("Enter a number searched:"))
# 二分法查找
left, right = 0, len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] == search_num:
print(mid)
break
elif lst[mid] > search_num:
right = mid - 1
else:
left = mid + 1
else:
print(-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
4
```
阅读全文