Understanding Java Recursive Array Reversal

  • Context: Comp Sci 
  • Thread starter Thread starter apiwowar
  • Start date Start date
  • Tags Tags
    Array Java Reverse
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
apiwowar
Messages
94
Reaction score
0
supposed to reverse an array of strings recursively. this is in a class that has an array object.

i came up with what's 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, shouldn't it just run through swapping first and last?

Code:
// 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);

    }
}
 
Physics news on Phys.org
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.