// this is the first array int firstArray [] = {5 , 7, 98 , 44, 33 }; // this is how you make the second array int secondArray[] = new int[firstArray.length];
Now you have to insert the above two arrays within a for loop to make the copy in reverse direction.
for(int i = firstArray.length - 1 ; i >= 0 ; i--){ secondArray[firstArray.length - 1- i]=firstArray[i]; }
wow now the secondArray is the mirror image of the first one. This method as you can see does not modify the firstArray. What you can do is make firstArray refer to the secondArray. Like this
firstArray = secondArray;
Now you may be wondering what happened to the firstArray memory segment. Well that will be garbage collected by the garbage collector because there is no reference to it in the code. Hey but this method is not recommended because it makes another copy of the original.
The one iam gonna show you below actually does the modification within the first array itself without requiring another array. but this method is a bit tricky. If i have time in the future i will show you how this code segment works using a diagram.
public static void mirror_int_array(int[] array) { if (array.length % 2 == 0) { int temp = 0; for (int i = 0; i < array.length / 2 - 1; i++) { temp = array[i]; array[i] = array[array.length - 1 - i]; array[array.length - 1 - i] = temp; } } else { int temp = 0; for (int i = 0; i < (array.length + 1) / 2 - 1; i++) { temp = array[i]; array[i] = array[array.length - 1 - i]; array[array.length - 1 - i] = temp; } } }
No comments:
Post a Comment