定义并初始化一个已经排好序的整型数组(包含10个整数,由大到小),编写函数实现以下功能:1)输入一个整数,按原来的排序规律将该数插入数组中;2)输入一个序号,要求在函数中实现将该序号对应(不用指针)
时间: 2025-02-23 22:34:48 浏览: 60
在Python中,我们可以定义一个已排序的整数列表(这里假设是降序排列)并实现所需的功能。首先,我们需要创建一个列表,然后定义两个函数,一个是`insert_sorted`用于插入新数,另一个是`get_element_by_index`用于获取指定序号的元素。
```python
def create_sorted_array(n=10):
return sorted(range(10, -1, -1), reverse=True)
def insert_sorted(array, num):
# 插入操作保持列表有序
index = len(array)
while index > 0 and array[index - 1] < num:
index -= 1
array.insert(index, num)
return array
def get_element_by_index(array, index):
# 检查索引是否越界,并返回对应的元素
if index >= 0 and index < len(array):
return array[index]
else:
raise IndexError("Index out of range")
# 初始化数组
sorted_array = create_sorted_array()
# 示例用法
print("Original array:", sorted_array)
num_to_insert = int(input("Enter a number to insert (or 'q' to quit): "))
while num_to_insert != 'q':
sorted_array = insert_sorted(sorted_array, num_to_insert)
print("Array after inserting:", sorted_array)
index = int(input("Enter an index to get element (or 'q' to quit): "))
try:
result = get_element_by_index(sorted_array, index)
print(f"Element at index {index} is: {result}")
except IndexError as e:
print(e)
```
当你运行这个程序时,它会提示用户输入数字和索引,按照指定规则进行操作。注意,当索引超出范围时,`get_element_by_index`函数会抛出异常。
阅读全文
相关推荐


















