2. 定义长度为3的整型数组,采用函数调用实现按照从大到小的顺序排序。在主函数中输出排序前和排序后的数组。按以下四种方法实现: (1)实参、形参为数组名; (2)实参为数组名,形参为指针变量; (3)实参为指针变量,形参为数组名; (4)实参为指针变量,形参为指针变量。
时间: 2024-03-20 08:43:27 浏览: 68
好的,我会尽力给予解答。
首先,我们可以通过实现一个排序函数来对数组进行排序。下面是一个简单的冒泡排序函数:
```c++
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
接下来,我们来逐个实现四种方法:
(1)实参、形参为数组名
```c++
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n);
int main() {
int arr[] = {3, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "排序前:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
bubbleSort(arr, n);
cout << "排序后:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
(2)实参为数组名,形参为指针变量
```c++
#include <iostream>
using namespace std;
void bubbleSort(int *arr, int n);
int main() {
int arr[] = {3, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "排序前:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
bubbleSort(arr, n);
cout << "排序后:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
void bubbleSort(int *arr, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (*(arr + j) < *(arr + j + 1)) {
int temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
}
```
(3)实参为指针变量,形参为数组名
```c++
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n);
int main() {
int arr[] = {3, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int *p = arr;
cout << "排序前:" << endl;
for (int i = 0; i < n; i++) {
cout << *(p + i) << " ";
}
cout << endl;
bubbleSort(p, n);
cout << "排序后:" << endl;
for (int i = 0; i < n; i++) {
cout << *(p + i) << " ";
}
cout << endl;
return 0;
}
void bubbleSort(int *arr, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
(4)实参为指针变量,形参为指针变量
```c++
#include <iostream>
using namespace std;
void bubbleSort(int *arr, int n);
int main() {
int arr[] = {3, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int *p = arr;
cout << "排序前:" << endl;
for (int i = 0; i < n; i++) {
cout << *(p + i) << " ";
}
cout << endl;
bubbleSort(p, n);
cout << "排序后:" << endl;
for (int i = 0; i < n; i++) {
cout << *(p + i) << " ";
}
cout << endl;
return 0;
}
void bubbleSort(int *arr, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (*(arr + j) < *(arr + j + 1)) {
int temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
}
```
以上就是四种方法的实现方式,你可以运行代码来验证它们的正确性。
阅读全文