酷代码 AI
菜单

编程实现选择排序函数。void selectionSort(int arr[], int n);。其中arr存放待排序的数据,n为数组长度(1≤n≤1000)。 函数接口定义如下: /* 对长度为n的数组arr执行选择排序 */ void selectionSort(int arr[], int n); 请实现selectionSort函数,使排序后的数据从小到大排列。 裁判测试程序样例: #include <stdio.h> #define N 1000 int arr[N]; /* 对长度为n的数组arr执行选择排序 */ void selectionSort(int arr[], int n); /* 打印长度为n的数组arr */ void printArray(int arr[], int n); void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } int main() { int n, i; scanf("%d", &n);

```c /* 对长度为n的数组arr执行选择排序 */ void selectionSort(int arr[], int n) { int i, j, min_idx; // 遍历数组 for (i = 0; i < n - 1; i++) { // 假设当前元素是最小的 min_idx = i; // 在剩余部分中找到最小元素 for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // 如果最小元素不是当前元素,交换它们 if (min_idx != i) swap(&arr[min_idx], &arr[i]); } } ``` [2025-12-10 23:09:18 | AI问答 | 167点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多