Comp Sci Understanding Java Recursive Array Reversal

AI Thread Summary
The discussion focuses on a Java method intended to reverse an array of strings recursively but produces an unexpected order. The array, initially containing five elements, is printed in a sequence that does not align with the expected reversed order. The code uses a recursive helper method to swap elements, but there is confusion regarding the termination condition and the logic used to handle the swapping. Participants suggest hand-simulating the process to understand the recursive calls and their effects on the array. The conversation emphasizes the importance of correctly implementing base cases and understanding recursion in the reversal process.
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.
 

Similar threads

Replies
3
Views
1K
Replies
2
Views
1K
Replies
3
Views
1K
Replies
5
Views
2K
Replies
21
Views
3K
Replies
4
Views
1K
Replies
7
Views
2K
Back
Top