编写子程序,实现整数数组的选择排序,在主函数中输入数据,并在主函数中输出排序好的数据
时间: 2023-06-18 15:08:57 浏览: 37
以下是实现整数数组选择排序的子程序示例:
```python
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
```
在主函数中,可以按照以下方式输入数据、调用子程序并输出排序好的数据:
```python
# 输入数据
arr = list(map(int, input("请输入整数数组,用空格分隔:").split()))
# 调用子程序进行排序
selection_sort(arr)
# 输出排序好的数据
print("排序后的数组为:", arr)
```
示例输出:
```
请输入整数数组,用空格分隔:4 2 7 1 3
排序后的数组为: [1, 2, 3, 4, 7]
```
相关问题
C++编写子程序,实现整数数组的选择排序,在主函数中输入数据,并在主函数中输出排序好的数据
以下是C++代码实现选择排序:
```cpp
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(arr[min_idx], arr[i]);
}
}
int main()
{
int n;
cout << "请输入数组长度:";
cin >> n;
int arr[n];
cout << "请输入数组元素:";
for(int i = 0; i < n; i++)
{
cin >> arr[i];
}
selectionSort(arr, n);
cout << "排序后的数组为:";
for(int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
```
输入样例:
```
请输入数组长度:5
请输入数组元素:4 2 7 1 8
```
输出样例:
```
排序后的数组为:1 2 4 7 8
```
请用C语言编写如下程序:.设计一个子函数,对任意n个整数排序,并在主函数中输入10个整数,调用此函数排序。
以下是用C语言编写的程序,实现对任意n个整数排序的功能:
```c
#include <stdio.h>
void sort(int arr[], int n); // 声明排序函数
int main()
{
int n = 10; // 排序的元素个数
int arr[n]; // 声明要排序的数组
int i;
// 输入要排序的元素
printf("请输入%d个整数:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
sort(arr, n); // 调用排序函数
// 输出排序后的结果
printf("排序后的结果为:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
// 实现选择排序算法
void sort(int arr[], int n)
{
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
```
该程序中,sort函数实现了选择排序算法,可以对任意n个整数进行排序。在主函数中,先声明要排序的数组,然后输入10个整数,并调用sort函数进行排序,最后输出排序后的结果。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)