1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java reverse array recusively

  1. Sep 26, 2011 #1
    supposed to reverse an array of strings recursively. this is in a class that has an array object.

    i came up with whats below. but it reverses the array in a weird order. the array is a 5 element array, the elements are {hello, how, are you, ?}. i passed in the object and after printed out the array and it came out as are hello you how ? which makes no sense to me.

    im not sure why it printed out like that, shouldnt it just run through swapping first and last?

    Code (Text):
    // reverse an array
    public void rev()
    {
        rev(0,a.length-1);
    }

    private void rev(int first, int last)
    {
        if(last == 0)
        {
        //do nothing
        }

        else
        {


        String temp = a[first];
        a[first] = a[last];
        a[last] = temp;

       
        rev(first+ 1, last-1);

        }
    }
     
  2. jcsd
  3. Sep 26, 2011 #2

    Mark44

    Staff: Mentor

    Take a piece of paper and a pencil, and hand-simulate what is happening to your array (which I assume is an array of character strings).

    The first call to rev comes in your main function. What happens? What happens in the recursive call to rev. Follow all the way through until last is 0.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java reverse array recusively
  1. Arrays in Java (Replies: 3)

  2. Java Reverse (Replies: 4)

  3. Java class Arrays (Replies: 1)

Loading...