用C语言写一个选择排序
时间: 2023-12-29 11:47:34 浏览: 22
下面是用C语言实现选择排序的代码:
```c
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++) {
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; 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]);
selectionSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
```
在以上代码中,我们定义了一个 `selectionSort()` 函数,该函数接受两个参数:需要排序的数组 `arr` 和数组的大小 `n`。选择排序的实现方式是从未排序的数组中找到最小值,然后将其放到已排序的数组的末尾。该过程重复进行,直到整个数组都被排序。在主函数中,我们定义了一个整数数组,然后将其传递给 `selectionSort()` 函数进行排序。最后,我们使用 `printf()` 函数输出排序后的数组。