Search code examples
javaprintingreverse

Reverse Print Given Array


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


Solution

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