怎么用C语言编写选择排序
时间: 2024-02-08 08:40:40 浏览: 21
选择排序是一种简单的排序算法,它的基本思想是每次从未排序的数组中选择最小的元素,放到已排序的数组的末尾。
下面是用C语言编写选择排序的示例代码:
```c
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n-1; i++) {
minIndex = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = 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;
}
```
在这个示例代码中,我们定义了一个`selectionSort()`函数,它接受一个整数数组`arr`和数组的大小`n`作为参数。函数内部使用两个循环,第一个循环从数组的第一个元素到倒数第二个元素进行迭代,第二个循环从当前元素的下一个元素到数组的最后一个元素进行迭代,用来查找未排序数组中最小的元素。在内部循环结束后,将最小元素与当前元素进行交换。
在`main()`函数中,我们定义了一个整数数组`arr`,并使用`sizeof()`函数计算数组的大小。然后,我们调用`selectionSort()`函数对数组进行排序,并打印排序后的数组。