用选择法对10个数排序
时间: 2023-11-20 16:05:35 浏览: 48
好的,以下是使用选择排序法对10个数进行排序的步骤:
1. 首先,我们从这10个数中选出最小的一个数,将其放在第一个位置上;
2. 然后,从剩下的9个数中选出最小的一个数,将其放在第二个位置上;
3. 以此类推,直到将所有的数都排好序为止。
下面是具体的实现过程:
```python
def selection_sort(arr):
n = len(arr)
for i in range(n-1):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
# 测试
arr = [64, 25, 12, 22, 11, 75, 37, 29, 88, 44]
print(selection_sort(arr))
```
输出结果为:
```
[11, 12, 22, 25, 29, 37, 44, 64, 75, 88]
```
相关问题
C语言用选择法对10个数排序
以下是C语言使用选择排序法对10个数进行排序的代码示例:
```c
#include <stdio.h>
int main()
{
int array[11], i, j, min, temp;
printf("请输入10个数:\n");
for (i = 1; i <= 10; i++)
scanf("%d", &array[i]);
printf("输入的数组为:\n");
for (i = 1; i <= 10; i++)
printf("%5d", array[i]);
printf("\n");
// 选择排序法
for (i = 1; i <= 9; i++)
{
min = i;
for (j = i + 1; j <= 10; j++)
{
if (array[min] > array[j])
min = j;
}
if (min != i)
{
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
printf("排序后的数组为:\n");
for (i = 1; i <= 10; i++)
printf("%5d", array[i]);
printf("\n");
return 0;
}
```
用选择法函数对10个数排序
好的,这里是用选择法函数对10个数排序的示例代码:
```python
def selection_sort(arr):
n = len(arr)
for i in range(n):
# 找到未排序部分中的最小值
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
# 将最小值与未排序部分的第一个元素交换位置
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
# 测试代码
arr = [3, 5, 1, 7, 2, 9, 4, 8, 6, 0]
sorted_arr = selection_sort(arr)
print(sorted_arr)
```
这个函数接受一个包含10个数的列表,使用选择法对列表进行排序,并返回排序后的列表。你可以将你想要排序的10个数传递给这个函数,它会返回已排序的结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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)