若有数组arr[10] = {36,1,26,40,32,23,98,77,2,25},写一个bubbleSort函数,通过一个指针数组aptr[10]对arr进行排序。要求不能改变arr数组顺序,最后把arr和aptr的所有元素输出并对比
时间: 2024-05-10 09:16:03 浏览: 7
实现bubbleSort函数的代码如下:
```
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]);
}
}
}
}
```
其中,参数arr是待排序的数组,参数aptr是指向arr中元素的指针数组,n是arr数组的长度。函数内部通过比较aptr数组中元素所指向的arr数组元素的大小来实现排序。
完整的代码如下:
```
#include <iostream>
using namespace std;
void bubbleSort(int* arr, int* aptr[], int n);
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 << "aptr: ";
for (int i = 0; i < 10; i++) {
cout << *(aptr[i]) << " ";
}
cout << endl;
return 0;
}
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]);
}
}
}
}
```
输出结果为:
```
arr: 36 1 26 40 32 23 98 77 2 25
aptr: 1 2 23 25 26 32 36 40 77 98
```
可以看到,arr数组的顺序没有改变,而aptr数组中的元素已经按照arr数组中元素的大小排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)