#include <stdio.h> #define N 10 int fun ( int *a, int n ); int main( ) { int x, b[N]={11,5,12,0,3,6,9,7,10,8}, n=10, i; for ( i=0; i<n; i++ ) printf("%d ", b[i]); printf("\n"); fun ( b, n ); for ( i=0; i<n; i++ ) printf("%d ", b[i]); printf("\n"); return 0; } 完善代码
时间: 2024-01-14 16:02:32 浏览: 18
根据题目要求,我们需要编写一个函数 `fun` 来对数组进行排序。因此,可以在代码中加入如下函数:
```c
int fun(int *a, int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
return 0;
}
```
这个函数使用冒泡排序算法对数组进行排序。它接收一个指向整型数组的指针 `a` 和数组的长度 `n` 作为输入,在原地对数组进行排序。排序完成后,函数返回 0。
在主函数中,我们可以调用这个函数来对数组进行排序,然后输出排序后的数组。完整的代码如下:
```c
#include <stdio.h>
#define N 10
int fun(int *a, int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
return 0;
}
int main() {
int x, b[N] = {11, 5, 12, 0, 3, 6, 9, 7, 10, 8}, n = 10, i;
for (i = 0; i < n; i++) printf("%d ", b[i]);
printf("\n");
fun(b, n);
for (i = 0; i < n; i++) printf("%d ", b[i]);
printf("\n");
return 0;
}
```
这段代码会先输出原始的数组,然后调用 `fun` 函数对数组进行排序,最后输出排序后的数组。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)