Java array inversion
//Method 1public class ArrayReverse{ public static void main(String[] args) { //Define array int[] arr = {11, 22, 33, 44, 55, 66}; //1. Exchange arr[0] and arr[5] {66, 22, 33, 44, 55, 11} //2. Exchange arr[1] and arr[4] {66, 55, 33, 44, 22, 11} //3. Exchange arr[2] and arr[3] {66, 55, 44, 33, 22, 11} //4. A total of 3 exchanges = / 2 //5. Each time the exchange, the corresponding subscripts are arr[i] and arr[ - 1 - i] //Code int temp = 0; int len = ; for(int i = 0; i < len/2 ;i++){ temp = arr[len - 1 - i]; arr[len - 1 - i] = arr[i]; arr[i] = temp; } } } //Method 2public class ArrayReverse{ public static void main(String[] args) { //Define array int[] arr1 = {11, 22, 33, 44, 55, 66}; //Use reverse order assignment method //1. Create a new array arr2 first, size //2. Inverse order traversal arr, copy each element into the element of arr2 (sequential copy) //3. It is recommended to add a loop variable j -> 0 -> 5 int[] arr2 = new int[]; for(int i = -1, j = 0; i>=0; i--, j++){ arr2[j] = arr1[i]; } //4. When the for loop is finished, arr2 is an inverse array //5. Let arr point to the data space of arr2. At this time, the original data space of arr is useless and variable reference will be treated as garbage and destroyed. arr1 = arr2; } }
Java array inversion Reverse
Three ways to invert arrays
public class ReverseArray { public static void main(String[] args) { int[] arr = {11,22,33,55,66,88}; printArray(arr); reverse0(arr); reverse1(arr); reverse2(arr); } public static void reverse0(int[] arr) { for(int i=0; i</2; i++) { int tem = arr[i]; arr[i] = arr[-1-i]; arr[-1-i] = tem; } printArray(arr); } public static void reverse1(int[] arr) { for(int start=0,end=-1;start<end;start++,end--) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; } printArray(arr); } public static void reverse2(int[] arr) { int[] tem = new int[]; for(int i=0; i<; i++) { tem[i] = arr[-1-i]; } printArray(tem); } public static void printArray(int[] arr) { for(int i=0; i<; i++) { if(==1) { ("["+arr[0]+"]"); } else if(i==0) { ("["+arr[0]+","); } else if(i==-1) { (arr[i]+"]"); } else { (arr[i]+","); } } } }
Running results:
[11,22,33,55,66,88]
[88,66,55,33,22,11]
[11,22,33,55,66,88]
[88,66,55,33,22,11]
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.