c语言中选择排序的完整代码
时间: 2023-09-24 19:06:05 浏览: 36
以下是 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;
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
```
在这个示例中,我们定义了 `selectionSort` 函数来执行选择排序,并定义了 `printArray` 函数来打印排序后的数组。在 `main` 函数中,我们初始化了一个整数数组,并将其大小存储在变量 `n` 中。我们然后调用 `selectionSort` 函数来对数组进行排序,并调用 `printArray` 函数来打印排序后的结果。