Understanding Java Recursive Array Reversal

  • Context: Comp Sci 
  • Thread starter Thread starter apiwowar
  • Start date Start date
  • Tags Tags
    Array Java Reverse
Click For Summary
SUMMARY

The discussion centers on a Java method for recursively reversing an array of strings, specifically an array containing five elements: {"hello", "how", "are you", "?"}. The provided implementation incorrectly outputs the array as {"are", "hello", "you", "how", "?"} instead of the expected reversed order. The issue arises from the base case condition in the recursive method, which checks if 'last' equals 0, leading to premature termination of the recursion. Correcting the base case to check if 'first' is greater than or equal to 'last' will resolve the issue.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with recursion concepts
  • Knowledge of array data structures in Java
  • Experience with debugging Java code
NEXT STEPS
  • Review Java recursion techniques and best practices
  • Learn about debugging strategies in Java
  • Explore array manipulation methods in Java
  • Study the concept of base cases in recursive functions
USEFUL FOR

Java developers, computer science students, and anyone interested in mastering recursive algorithms and array manipulation in Java.

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 ·
Replies
3
Views
1K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K