1.已知含有10个整数的查找表如下:(9,13,15,7,45,32,56,89,60,36),从键盘上输入一个整数,用顺序查找的方法在查找表中查找该整数。若存在,输出该元素的下标值,否则,给出相应的信息。 2.对有序数据表(5,7,9,12,15,18,20,22,25,30,100),编写程序按折半查找方法查找12和28。
时间: 2023-08-08 16:07:56 浏览: 206
10个整数排序与查找
1. 顺序查找的代码实现如下:
```python
# 定义查找函数
def sequential_search(lst, x):
for i in range(len(lst)):
if lst[i] == x:
return i
return -1 # 如果未找到,返回-1
# 测试
lst = [9, 13, 15, 7, 45, 32, 56, 89, 60, 36]
x = int(input("请输入要查找的整数:"))
index = sequential_search(lst, x)
if index == -1:
print("未找到该整数")
else:
print("该整数的下标为:", index)
```
2. 折半查找的代码实现如下:
```python
# 定义查找函数
def binary_search(lst, x):
low, high = 0, len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == x:
return mid
elif lst[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1 # 如果未找到,返回-1
# 测试
lst = [5, 7, 9, 12, 15, 18, 20, 22, 25, 30, 100]
x1 = 12
x2 = 28
index1 = binary_search(lst, x1)
index2 = binary_search(lst, x2)
if index1 == -1:
print("未找到", x1)
else:
print(x1, "的下标为:", index1)
if index2 == -1:
print("未找到", x2)
else:
print(x2, "的下标为:", index2)
```
输出结果为:
```
12 的下标为: 3
未找到 28
```
阅读全文