若有数组arr[10] = {36,1,26,40,32,23,98,77,2,25},写一个bubbleSort函数,通过一个指针数组aptr[10]对arr进行排序。要求不能改变arr数组顺序,最后把arr和aptr的所有元素输出并对比
时间: 2023-10-05 19:12:54 浏览: 29
下面是 bubbleSort 函数的实现代码:
```c++
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])) {
int* temp = aptr[j];
aptr[j] = aptr[j + 1];
aptr[j + 1] = temp;
}
}
}
}
```
使用方法:
```c++
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];
}
bubbleSort(arr, aptr, 10);
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)
![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)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)