若有数组 arr[10]={36,1,26,40,32,23,98,77,2,25},写一个 bubbleSort 函数,通过一个指针数组aptr[10]对 arr 进行排序。要求不能改变 arr 数组顺序,最后把 arr 和aptr 的所有元素输出并对比
时间: 2024-05-04 08:20:05 浏览: 16
下面是一个基于指针数组的冒泡排序实现:
```c++
#include <iostream>
using namespace std;
void bubbleSort(int* arr, int* aptr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (*(aptr[j]) > *(aptr[j+1])) {
swap(aptr[j], aptr[j+1]);
}
}
}
}
int main() {
int arr[10] = {36,1,26,40,32,23,98,77,2,25};
int* aptr[10];
for (int i = 0; i < 10; i++) {
aptr[i] = &arr[i]; // 将指针数组元素指向 arr 数组
}
bubbleSort(arr, aptr, 10);
// 输出排序后的 arr 数组和 aptr 数组
cout << "arr: ";
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "aptr: ";
for (int i = 0; i < 10; i++) {
cout << *(aptr[i]) << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
arr: 36 1 26 40 32 23 98 77 2 25
aptr: 1 2 23 25 26 32 36 40 77 98
```
可以看到,arr 数组的元素顺序没有改变,而 aptr 数组的元素顺序已经按照从小到大排序。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)