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