一行一行解释一下这个代码:#include <stdio.h> void selection_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int min_index = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[min_index]) { min_index = j; } } if (min_index != i) { int temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } for (int j = 0; j < n; j++) { if(j!=n-1) printf("%d ", arr[j]); else printf("%d", arr[j]); } printf("\n"); } } int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } selection_sort(arr, n); printf("\n"); } return 0; }
时间: 2024-03-14 14:42:48 浏览: 27
这段代码实现了选择排序,并且实现了对每一轮排序后数组的输出。下面我会逐行解释代码的含义:
```c
#include <stdio.h>
```
引入了标准输入输出库。
```c
void selection_sort(int arr[], int n) {
```
定义一个名为selection_sort的函数,它接受一个整数数组arr和数组长度n作为参数。
```c
for (int i = 0; i < n - 1; i++) {
```
第一个for循环,从0到n-2遍历每一个元素,因为在最后一轮排序之后,最后一个元素一定是最大的,不需要再进行排序。
```c
int min_index = i;
```
定义一个名为min_index的整数变量,用来记录未排序部分的最小值的索引。
```c
for (int j = i + 1; j < n; j++) {
```
第二个for循环,从i+1到n-1遍历未排序部分的元素。
```c
if (arr[j] < arr[min_index]) {
```
如果当前元素比最小值还小,则更新最小值的索引。
```c
if (min_index != i) {
```
如果最小值不是当前元素所在的位置,则交换最小值和当前元素的位置。
```c
for (int j = 0; j < n; j++) {
if(j!=n-1)
printf("%d ", arr[j]);
else
printf("%d", arr[j]);
}
```
输出本轮排序后的数组。
```c
printf("\n");
```
输出换行符,以便下一轮排序的输出能够独立一行。
```c
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
selection_sort(arr, n);
printf("\n");
}
return 0;
}
```
定义主函数,首先读入测试数据组数t,然后对于每组数据,读入数组长度n和数组元素,调用selection_sort函数进行排序,并在每一轮排序后输出数组。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)