用指針與數組作為函數參數,以「擂台法」(選擇排序)對一維實型數組 a[10] 進行降序排序。要求展示四種參數傳遞組合:
測試數據:10, 25, 90, 80, 70, 35, 65, 40, 55, 5
// 原代碼 Sort2 中
temp = *(pa + max);
*(pa + max) = *(pa + j); // 錯誤:j 循環結束時為 n,導致訪問 pa[n] 越界
*(pa + j) = temp;
修正:應與外層循環變量 i 交換:
*(pa + max) = *(pa + i);
*(pa + i) = temp;
// 原代碼
for (j = 0; j < n; j++) // 錯誤:應從 i+1 開始,避免重複比較已排序部分
修正:
for (j = i + 1; j < n; j++)
Sort1 中同樣需修正。
#include <iostream>
using namespace std;
void Sort1(int a1[], int n) { // 形參為數組
int i, j, temp, max;
for (i = 0; i < n - 1; i++) {
max = i;
for (j = i + 1; j < n; j++) {
if (a1[max] < a1[j]) max = j;
}
temp = a1[max];
a1[max] = a1[i];
a1[i] = temp;
}
for (i = 0; i < n; i++) cout << a1[i] << " ";
cout << endl;
}
int *Sort2(int *pa, int n) { // 形參為指針
int i, j, temp, max;
for (i = 0; i < n - 1; i++) {
max = i;
for (j = i + 1; j < n; j++) {
if (*(pa + max) < *(pa + j)) max = j;
}
temp = *(pa + max);
*(pa + max) = *(pa + i);
*(pa + i) = temp;
}
return pa;
}
int main() {
int a[] = {10, 25, 90, 80, 70, 35, 65, 40, 55, 5};
int *p = a;
int t;
// 情況1:實參數組名,形參數組
Sort1(a, 10);
// 情況2:實參數組名,形參指針
int *sort_2 = Sort2(a, 10);
for (t = 0; t < 10; t++) cout << *(sort_2 + t) << " ";
cout << endl;
// 情況3:實參指針,形參數組
Sort1(p, 10);
// 情況4:實參指針,形參指針
int *sort_4 = Sort2(p, 10);
for (t = 0; t < 10; t++) cout << *(sort_4 + t) << " ";
cout << endl;
return 0;
}
int a[] 或指針 int *a,效果等價。i+1 尋找最大值下標,最後與 i 交換。*(pa + i) 等價於 pa[i],靈活運用。