编程实现如下功能: (1)根据输入的查找表的表长n和n个关键字值,建立顺序查找表,并在此查找表中用顺序查找方法查找给定关键值的记录,最后输出查找结果。 (2)根据输入的查找表的表长n和n个按升排列的关键字值,建立有序顺序查找表,并在此查找表中用二分查找方法查找给定关键值的记录,最后输出查找结果。 (3)主程序中要求设计一个菜单,允许用户通过菜单来多次选择执行哪一种查找操作。
时间: 2024-03-27 10:40:43 浏览: 5
下面是一个实现上述功能的 Python 代码,其中使用了类来实现查找表:
```python
class SeqSearchTable:
def __init__(self, n, keys):
self.n = n
self.keys = keys
def search(self, key):
for i in range(self.n):
if self.keys[i] == key:
return i
return -1
class OrderedSeqSearchTable:
def __init__(self, n, keys):
self.n = n
self.keys = keys
def search(self, key):
left, right = 0, self.n - 1
while left <= right:
mid = (left + right) // 2
if self.keys[mid] == key:
return mid
elif self.keys[mid] > key:
right = mid - 1
else:
left = mid + 1
return -1
def main():
while True:
print("请选择操作类型:")
print("1. 建立顺序查找表并进行顺序查找")
print("2. 建立有序顺序查找表并进行二分查找")
print("3. 退出程序")
choice = int(input("请输入选择:"))
if choice == 1:
n = int(input("请输入表长:"))
keys = []
for i in range(n):
key = int(input(f"请输入第{i+1}个关键字值:"))
keys.append(key)
table = SeqSearchTable(n, keys)
key = int(input("请输入要查找的关键值:"))
index = table.search(key)
if index == -1:
print("查找失败")
else:
print(f"查找成功,关键值所在位置为{index}")
elif choice == 2:
n = int(input("请输入表长:"))
keys = []
for i in range(n):
key = int(input(f"请输入第{i+1}个关键字值:"))
keys.append(key)
table = OrderedSeqSearchTable(n, keys)
key = int(input("请输入要查找的关键值:"))
index = table.search(key)
if index == -1:
print("查找失败")
else:
print(f"查找成功,关键值所在位置为{index}")
elif choice == 3:
break
else:
print("选择无效,请重新输入")
if __name__ == '__main__':
main()
```
在程序中,我们先定义了两个类 `SeqSearchTable` 和 `OrderedSeqSearchTable`,分别对应无序顺序查找表和有序顺序查找表。这两个类都有一个 `search` 方法,用于查找给定的关键值。在主函数中,我们使用一个无限循环,每次循环让用户选择要执行的操作类型,然后根据用户的选择分别进行顺序查找和二分查找。如果用户选择退出程序,则退出循环并结束程序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)