Monday, April 11, 2011

take mirror image of a int array in java

Okay so lets say you have a array and you just wanna take the mirror image of it. how do you do it ? well there are several ways of doing it. One way is to just make another array , copy the first one to the second one by looping through the first one in the reverse direction. like this.

// 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