使用函数的选择法排序
时间: 2024-06-18 12:03:11 浏览: 19
使用函数的选择排序是一种简单但是高效的排序算法,其基本思路是从未排序的数列中选择最小的数,然后将它放到数列的起始位置,接着从剩余的未排序元素中继续寻找最小元素,放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。下面是使用函数的选择排序的基本步骤:
1.定义一个函数selection_sort,接收一个整数数组和数组长度作为参数。
2.使用for循环遍历数组,每次循环找出未排序部分中最小的元素,并将其与未排序部分的第一个元素交换。
3.重复第二步直到数组被完全排序。
以下是使用函数的选择排序的示例代码:
```
void selection_sort(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;
// 将最小元素与未排序部分的第一个元素交换
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
```
相关问题
c语言 使用函数的选择法排序
以下是使用函数的选择法排序的C语言代码:
```c
#include <stdio.h>
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;
}
}
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果为:
```
Sorted array: 11 12 22 25 64
```
7-4 使用函数的选择法排序
以下是使用函数的选择法排序的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]
```
在这个函数中,我们首先获取数组的长度。然后,我们循环遍历数组,每次选择当前未排序部分的最小元素,并将其与当前位置交换。在这个过程中,我们使用两个嵌套的循环:外循环遍历数组,内循环查找最小元素的索引。最后,我们返回已排序的数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)