Answer the question
In order to leave comments, you need to log in
How is the recursion base achieved in this example?
Sedgwick has this example in his homework:
public static String mystery(String s)
{
int N = s.length();
if (N <= 1) return s;
String a = s.substring(0, N/2);
String b = s.substring(N/2, N);
return mystery(b) + mystery(a);
}
This method reverses the string. Explain to someone far from recursive methods how the recursion base is achieved here?
Answer the question
In order to leave comments, you need to log in
This method splits the string in half and swaps the halves. Already half of the lines are passed to internal calls. Bisection is finite - at some point, the string fragment will be of length 1 or 0. To reverse a string of length one or an empty string, nothing needs to be done, so if the length of the string <= 1, the same string is returned - this is how the base is reached .
Example. For convenience, we take numbers as symbols.
1) Data goes deep into recursive calls:
(12345)
((12) (345))
(((1) (2)) ((3) (45)))
When the function receives a string of length 1, it returns it. And the line "45" will go one step deeper. Meanwhile, in the calls that received data back, the results are swapped and the resulting string is returned:
((21) ((3) ((4) (5))))
((21) ((3) (54)))
((21) (543))
(54321)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question