7-4 使用函数的选择法排序
时间: 2024-06-12 08:04:25 浏览: 35
以下是使用函数的选择法排序的Python代码:
```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]
return arr
arr = [64, 25, 12, 22, 11]
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)
```
输出结果:
```
Sorted array: [11, 12, 22, 25, 64]
```
在这个函数中,我们首先获取数组的长度。然后,我们循环遍历数组,每次选择当前未排序部分的最小元素,并将其与当前位置交换。在这个过程中,我们使用两个嵌套的循环:外循环遍历数组,内循环查找最小元素的索引。最后,我们返回已排序的数组。
相关问题
实验7-1-4 选择法排序
选择排序是一种简单的排序算法,其基本思想是:首先在未排序的序列中找到最小(大)元素,然后将其存放到序列的起始位置;接着,再从剩余未排序的元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
算法步骤如下:
1. 在未排序序列中找到最小(大)元素,存放到排序序列的起始位置;
2. 从剩余未排序的元素中继续寻找最小(大)元素,然后放到已排序序列的末尾;
3. 重复步骤 2,直到所有元素均排序完毕。
下面是选择排序的示例代码:
```
#include <stdio.h>
void selection_sort(int arr[], int len)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < len-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < len; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selection_sort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
```
在上面的示例中,我们定义了一个 selection_sort 函数,它接受一个整数数组和数组长度作为参数,并使用选择排序算法对数组进行排序。在主函数中,我们定义了一个整数数组,然后调用 selection_sort 函数来排序该数组,并输出排序后的结果。
当我们运行这个程序时,输出结果应该为:
```
Sorted array:
11 12 22 25 64
```
这表明选择排序算法已成功对给定数组进行了排序。
6-4 使用函数的选择法排序 (25 分)
选择法排序是一种简单的排序算法,它的基本思想是每次从待排序的元素中选出最小(或最大)的一个元素,放在已排好序的元素的末尾,直到所有元素都排好序为止。在实现选择法排序时,可以使用函数来封装排序的过程,使得代码更加简洁和易于维护。具体实现时,可以定义一个选择排序函数,该函数接收一个待排序的数组作为参数,然后在函数内部使用循环和条件语句来实现排序的过程。在每次循环中,选择排序函数会找到当前未排序部分中的最小元素,并将其与未排序部分的第一个元素交换位置,从而将该元素放到已排序部分的末尾。最终,当所有元素都被排序后,选择排序函数会返回排好序的数组。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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_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)