实验7-1-4 选择法排序
时间: 2023-07-16 13:15:52 浏览: 53
选择排序是一种简单的排序算法,其基本思想是:首先在未排序的序列中找到最小(大)元素,然后将其存放到序列的起始位置;接着,再从剩余未排序的元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
算法步骤如下:
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
```
这表明选择排序算法已成功对给定数组进行了排序。