c语言编写一个函数,使用选择排序算法对数组元素进行升序排序。在主程序中调用这个函数并输出结果
时间: 2023-12-14 07:39:45 浏览: 251
以下是一个使用选择排序算法对数组进行升序排序的C语言函数:
```c
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;
}
}
```
在主程序中,我们可以声明一个数组并初始化它,然后调用上述函数对其进行排序。以下是一个示例程序:
```c
#include <stdio.h>
void selectionSort(int arr[], int n);
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]);
return 0;
}
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;
}
}
```
输出为:
```
Sorted array:
11 12 22 25 64
```
阅读全文