1
import java.util.*;
class Example{
    public static int[] reverse(int[]ar){
        for (int i = 0; i < (ar.length); i++)
        {
            ar[i]=ar[(ar.length-i-1)];
        }
        return ar;
        }
    public static void main(String args[]){
        int[] xr={10,20,30,40,50};
        System.out.println(Arrays.toString(xr)); 

        int[]y=xr;
        int[]z=reverse(xr);
        System.out.println(Arrays.toString(z));
    }
}

This code output get: [50,40,30,40,50].

But I want to print the reverse of the given Array. And I want to know how this output([50,40,30,40,50]) generated

Kayvan Tehrani
  • 3,070
  • 2
  • 32
  • 46
Yesitha
  • 75
  • 1
  • 5
  • You are overwriting the elements in the beginning, trying swapping them instead. – Shivam Mohan Feb 10 '20 at 10:53
  • you need a temporary array/variable. Right now, you over-write the first part of the array with the second part – jhamon Feb 10 '20 at 10:53
  • 1
    Does this answer your question? [How do I reverse an int array in Java?](https://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java) – jhamon Feb 10 '20 at 10:54

1 Answers1

0

When i=0

ar[i]=ar[(ar.length-i-1)]

assigns the last element of the array to the first index of the array. Thus the original first element of the array is overwritten before you have a chance to assign it to the last index.

This happens for all the indices of the first half of the array.

If you want to reverse the array in place, you need some temp variable, and you should make a swap in each iteration:

public static int[] reverse(int[]ar) 
{
    for (int i = 0; i < ar.length / 2; i++) {
        int temp = ar[i];
        ar[i] = ar[(ar.length-i-1)];
        ar[(ar.length-i-1)] = temp;
    }
    return ar;
}
Eran
  • 387,369
  • 54
  • 702
  • 768