Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: 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()

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


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

        rev(first+ 1, last-1);

  2. jcsd
  3. Sep 26, 2011 #2


    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook