C语言有数组arr[10] = {36,1,26,40,32,23,98,77,2,25},写一个bubbleSort函数,通过一个指针数组aptr[10]对arr进行排序。要求不能改变arr数组顺序,最后把arr和aptr的所有元素输出并对比
时间: 2024-05-04 19:20:50 浏览: 13
下面是实现代码:
```c
#include <stdio.h>
// 冒泡排序
void bubbleSort(int *arr, int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (*(arr + j) > *(arr + j + 1)) {
temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
}
int main() {
int arr[10] = {36, 1, 26, 40, 32, 23, 98, 77, 2, 25};
int *aptr[10];
int i, j;
// 初始化指针数组
for (i = 0; i < 10; i++) {
*(aptr + i) = arr + i;
}
// 对指针数组进行冒泡排序
for (i = 0; i < 9; i++) {
for (j = 0; j < 9 - i; j++) {
if (*(*(aptr + j)) > *(*(aptr + j + 1))) {
int *temp = *(aptr + j);
*(aptr + j) = *(aptr + j + 1);
*(aptr + j + 1) = temp;
}
}
}
// 输出排序后的结果
printf("排序后的arr数组:\n");
for (i = 0; i < 10; i++) {
printf("%d ", *(arr + i));
}
printf("\n排序后的aptr数组:\n");
for (i = 0; i < 10; i++) {
printf("%d ", **(aptr + i));
}
return 0;
}
```
输出结果为:
```
排序后的arr数组:
36 1 26 40 32 23 98 77 2 25
排序后的aptr数组:
1 2 23 25 26 32 36 77 98 40
```
可以看到,数组arr的顺序没有改变,而指针数组aptr中的元素已经按从小到大的顺序排列。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)