可以通過交換數組的元素來實現數組逆序排列。具體步驟如下:
temp
。i
個元素與倒數第i
個元素交換,即temp = arr[i]; arr[i] = arr[length-1-i]; arr[length-1-i] = temp;
。以下是一個完整的示例代碼:
#include <stdio.h>
void reverseArray(int arr[], int length) {
int temp; // 臨時變量
for (int i = 0; i < length / 2; i++) {
temp = arr[i];
arr[i] = arr[length - 1 - i];
arr[length - 1 - i] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
printf("原數組:");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
reverseArray(arr, length);
printf("\n逆序排列后的數組:");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
return 0;
}
輸出結果:
原數組:1 2 3 4 5
逆序排列后的數組:5 4 3 2 1