An array of reverse
- Requirement: Reverse the contents of the array elements. ArrayReverse.java
arr {11.22.33.44.55.66} {66.55.44.33.22.11}
Copy the code
Method 1: By finding a pattern reversal
- 【 答 案 】
- regular
The 1.arr[0]
和arr[5]
swapping,22,33,44,55,11 {66}
The 2.arr[1]
和arr[4]
swapping,55,33,44,22,11 {66}
The 3.arr[2]
和arr[3]
swapping,55,44,33,22,11 {66}
4. It’s a total swap3 times = arr.length / 2
5. For each swap, the corresponding subscript isArr [I] and ARr [arr. Length-1-i]
int temp = 0;
int len = arr.length; // Calculate the length of the array
for( int i = 0; i < len / 2; i++) {
temp = arr[len - 1 - i];/ / save
arr[len - 1 - i] = arr[i];
arr[i] = temp;
}
System.out.println("=== = flipped array ===");
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");/ / 66,55,44,33,22,11
}
Copy the code
Method 2: Use the reverse assignment mode arrayReverse02.java
- Train of thought
1. Create a new arrayarr2
, size,arr.length
2. Reverse traversalarr
, copy each element toarr2
(sequential copy)
3. It is recommended to add a loop variablej -> 0 -> 5
int[] arr2 = new int[arr.length];
// Reverse arR
for(int i = arr.length - 1, j = 0; i >= 0; i--, j++) {
arr2[j] = arr[i];
}
{66, 55, 44,33, 22, 11}
//5. Make arR point to arR2 data space, then there is no variable reference in arR original data space
// Will be disposed of as garbage
arr = arr2;
System.out.println("==== Elements of ARR =====");
//6. Output arR
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
Copy the code