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--;
        }
}
2

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

how do i modify in such a way that it then can be reversed?
@Jey.L I've added example code with a swap operation.
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;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.