-1

I have been trying to solve this problem of reversing an array function on Hacker Rank. I have been struggling with it. It is not reversing the array,though it is printing the same input it has been given.

static int[] reverse(int[] a) {
   int j;
   for(j = a.length-1;j>=0;j--){
       System.out.print(a[j]+" ");
   }
  return a;
}

2 Answers2

0

You can do something like this in O(n):

public class Test {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

            int arr[] =reverse(new int[]{1,2,3,4});
            for (int j = 0; j < arr.length; j++) {
                System.out.println(arr[j]);
            }

    }

    static int[] reverse(int[] a) {

           for(int i=0,j= a.length-1;i<j;i++,j--){

              int temp = a[j];
              a[j]=a[i];
              a[i]=temp;
           }
          return a;


}

}

Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
0

You are printing the array in a reverse way. It's not reverse an array. Just simple like this. You can find a better way.

 static int[] reverse(int[] a) {
     int[] b = new int[a.length];
     for (int i = a.length - 1; i >= 0; i--) {
         b[a.length - 1 - i] = a[i];
     }
     return b;
 }
Kai Pham
  • 19
  • 3