ReversalArray——The implementation method of Java language
Method 1:The order of the front and back is reversed
publicclassArray{publicstaticvoidmain(String[] args){int[] arr={1,2,5,7,3};//Statually initialize a set of arraysfor(int k=0;k<arr.length/2;k++){int w=arr[k];//Storage array elements with the help of the third variable
arr[k]=arr[arr.length-1-k];// Switch array elements corresponding to k and -1-k
arr[arr.length-1-k]=w;}for(int k =0; k <5; k++){System.out.print(arr[k]+" ");}}}
1
2
3
4
5
6
7
8
9
10
11
12
13
Method 2: Climb the two sides (the name you give me) - approaching
publicclassArray{publicstaticvoidmain(String[] args){int[] arr={1,2,3,4,5};// Static initializationfor(int m=0,n=4;m<n;m++,n--){//n=-1;int t=arr[m];
arr[m]=arr[n];
arr[n]=t;}for(int k =0; k <5; k++){System.out.print(arr[k]+" ");}}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Method 3: Create an empty array
publicclassArray{publicstaticvoidmain(String[] args){int[] arr={1,2,3,4,5};int[]A=newint[arr.length];//Create an empty array A of large size with arr to be usedfor(int i=0;i<arr.length;i++){//Invert the arr element and assign it to array A as a wholeA[i]= arr[arr.length-i-1];}for(int i=0;i<A.length;i++){//The purpose is to invert the original array. Then assign the inverted array A to the original array arr for output
arr[i]=A[i];System.out.print(arr[i]+" ");}}}