反转数组
创建新数组
static int[] reverse(int[] arr, int arrLength) {
int[] newArr = new int[arrLength];
for (int i = 0 ; i < arrLength ; i++){
newArr[i] = arr[arrLength - (i + 1)];
}
return newArr;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int[] newArr = reverse(arr, arr.length);
for(int num : newArr){
System.out.println(num);
}
}
首尾交换
static int[] reverse(int[] arr, int arrLength) {
for (int i = 0 ; i < arrLength/2 ; i++){
int temp = arr[i];
arr[i] = arr[arrLength - (i + 1)];
arr[arrLength - (i + 1)] = temp;
}
return arr;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
for(int num : arr){
System.out.println(num);
}
}