调用函数fun,功能是用选择法对10个整数按降序排序
时间: 2023-11-21 22:06:40 浏览: 84
以下是用选择排序法对10个整数按降序排序的 Python 代码:
```python
def fun(lst):
n = len(lst)
for i in range(n):
max_idx = i
for j in range(i+1, n):
if lst[j] > lst[max_idx]:
max_idx = j
lst[i], lst[max_idx] = lst[max_idx], lst[i]
return lst
# 测试
test_lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print(fun(test_lst)) # 输出 [9, 6, 5, 5, 4, 3, 3, 2, 1, 1]
```
函数 `fun` 的输入参数是一个包含10个整数的列表 `lst`,输出结果是按降序排序后的列表。函数内部使用选择排序算法,每次从未排序部分中选出最大的数,将其与未排序部分的最后一个数交换位置,直到所有数都排好序为止。
相关问题
c语言调用函数fun其功能是用选择法对10个整数按降序排序
以下是一个使用选择排序算法对10个整数按降序排序的C语言函数fun的实现:
```c
void fun(int arr[], int n) {
int i, j, temp, max_index;
for (i = 0; i < n - 1; i++) {
max_index = i;
for (j = i + 1; j < n; j++) {
if (arr[j] > arr[max_index]) {
max_index = j;
}
}
if (max_index != i) {
temp = arr[i];
arr[i] = arr[max_index];
arr[max_index] = temp;
}
}
}
```
该函数的参数包括一个包含10个整数的数组和数组的长度n。在函数内部,我们使用选择排序算法对数组进行降序排序。首先,我们从数组的第一个元素开始,找到数组中最大的元素,并将其与第一个元素交换。然后,我们从第二个元素开始,找到剩余元素中最大的元素,并将其与第二个元素交换。重复此过程,直到整个数组被排序。
使用c语言调用函数fun,功能是用选择法对10个整数按降序排序
以下是使用选择排序算法对10个整数进行降序排序的C语言代码:
```c
#include <stdio.h>
// 函数声明
void fun(int arr[], int n);
int main() {
int arr[10] = { 9, 6, 3, 7, 5, 2, 8, 1, 4, 0 };
int n = 10;
printf("排序前:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
fun(arr, n);
printf("\n排序后:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
// 函数定义
void fun(int arr[], int n) {
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
```
输出结果:
```
排序前:9 6 3 7 5 2 8 1 4 0
排序后:9 8 7 6 5 4 3 2 1 0
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)