# recursion and call stack problem

• 12-26-2009, 12:12 PM
OptimusPrime
recursion and call stack problem
i have this code,

static String reverse(String s) {
if (s.length() <= 1) {
return s;
}
return reverse(s.substring(1)) + s.charAt(0);
}

and these two questions,
1.Explain the algorithm.

2.Rewrite the recursion and implement it iteratively. Use the same method signature, but call the method reverseIterative. Use a while-loop in your implementation, and implement the same approach you answered in the previous question.

im new to recursions,
can anyone help and explain?
thanks.
OP
• 12-26-2009, 12:49 PM
JosAH
Thinking recursively is thinking lazy (I'm very good at it ;-) Reversing an empty String or a String with just one character in it is easy: simply do nothing; otherwise the String can be represented as fT where f is the first single character and T represents the rest of the String; let something/somebody (else) do the reversion of T and I append the single character f to it; effectively that reverses the entire String. (try it on paper).

You do the coding because it's your assignment.

kind regards,

Jos
• 12-26-2009, 07:46 PM
tim
Hi OptimusPrime

I've attached a PDF document explaining this recursive algorithm in detail. This should help you find an iterative algorithm for your assignment. Plagiarize at own loss. Please mind the typos.

Good luck
Tim
• 12-26-2009, 10:35 PM
OptimusPrime
thanks alot!
it helped!
:):):)
• 12-26-2009, 10:49 PM
tim