0

I am trying to reverse the array order..but to no avail. I understand that there are existing methods, but i do not understand why mine does not work? When i try to reverse Array of [1,2] i get [2,2], when trying [1,2,3] i get a reverse array of [3,2,3] instead. I cannot see what is wrong with my method..please help thanks!

      public static void reverseArray(int[] arr) {
        int j = arr.length-1;
        int [] temp = arr;

        for (int i=0; i<arr.length; i++){
          arr [i] = temp [j];
          j--;
        }
}
Jey.L
  • 45
  • 9
  • Possible duplicate of https://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java – jrook Sep 26 '19 at 16:13
  • Possible duplicate of [How do I reverse an int array in Java?](https://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java) – Michał Krzywański Sep 26 '19 at 16:33

2 Answers2

3

temp points to the same array as arr, so the array you're copying into is the same array you're copying out of. Your loop is equivalent to this:

int j = arr.length-1;

for (int i=0; i<arr.length; i++){
  arr [i] = arr[j];
  j--;
}

(note arr in both the source and the destination)

Either swap the array elements on every iteration, or have temp be a copy of arr:

for (int i = 0; i < arr.length / 2; i++) {
    int temp = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = temp;
}
Malt
  • 28,965
  • 9
  • 65
  • 105
1

That is because Java works with references, so when you assign temp = arr you are not duplicating the array, you are just creating another reference to the same array. That way, when you edit the array arr you are also editing the array temp.

Try this instead:

public static void reverseArray(int[] arr) {
    int[] temp = new int[arr.length];

    for (int i = 0,j = arr.length - 1; i < arr.length; i++,j--) {
      temp[i] = arr[j];
    }
    arr = temp;
  }
Malt
  • 28,965
  • 9
  • 65
  • 105
donkikote
  • 61
  • 1
  • 8