0

I know this question has been asked in other languages including Java itself.

I just want to clarify that I know how to reverse an array but I would rather appreciate help if any for this particular solution of mine. So please don't mark it as a duplicate.

import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
    /*
         Code for User input
    */

    /* The problem was with the Swapping Code below */
    for(int i=0; i<=n/2; i++)
        swap(i,n-i-1,a);

  /* Output Code. */

    }
/*Swap function*/
public static void swap(int x, int y, int[] arr){
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

}

I have changed my solution according to the links provided in the comments .I am getting alright in some of the test cases but in some, the code fails.I think I have done it correctly.So any help will be appreciated.Thanks

john400
  • 392
  • 4
  • 10
  • 20
  • 1
    You're just swapping two int variables which does nothing. What you need is swap the contents of the array. Something like `temp = a[x]; a[x] = a[y]; a[y] = temp;` – kjsebastian Oct 24 '16 at 03:35
  • 5
    Sorry, but I think this _should_ be marked as a duplicate of http://stackoverflow.com/questions/2393906/how-do-i-make-my-swap-function-in-java, because that solves your problem perfectly. – ajb Oct 24 '16 at 03:36
  • 1
    @ajb specifically the first snippet in [polygenelubricants's answer](http://stackoverflow.com/a/2393913/240443) there. – Amadan Oct 24 '16 at 03:38
  • I changed the code according to the snippet.But in some cases my code is failing.Can anyone just tell me what I am doing wrong now? – john400 Oct 24 '16 at 03:54
  • 1
    To form better question and make it an [MCVE] and easier to answer, replace all the input part with `String a[] = new String[]{/*an array which fails*/};` – c0der Oct 24 '16 at 04:17

1 Answers1

1

Thanks to conscells,ajb and Amadan to lead me to the correct place for getting a solution to this problem.

Here is the correct solution for reversing the array in Java.I know there are solutions provided for it already here but just thought to make this question somewhat useful for future users.Thanks.

import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int a[] = new int[n];
    for(int i=0; i < n; i++)
        a[i] = scan.nextInt();
    for(int i=0; i < n/2; i++)
        swap(i,n-i-1,a);
    for(int i = 0; i < n; i++)
        System.out.println(a[i]);
    }

public static void swap(int x, int y, int[] arr) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
  }
}
Sajad
  • 2,273
  • 11
  • 49
  • 92
john400
  • 392
  • 4
  • 10
  • 20