New CS student, studying for a final. I am trying to figure out how many times a recursive method will be called in general. Added the code as an example. If I input abcd and efgh, how many calls based on the size of the Strings? If n is any data size, the # of calls is n(?) in any recursive method.
public static String interweave(String s1, String s2)
{
if (s1.equals("") ) return s2;
else if (s2.equals("")) return s1;
else return "" + interweave(s1.substring(0,s1.length()-1), s2.substring(0,s2.length()-1))
+s1.charAt(s1.length()-1)+s2.charAt(s2.length()-1);
}
Notice that in your question, at each recursive step you reduce by one the size of both strings until either one of them has length zero (the base cases of the recursion). It’s easy to see that the number of recursive calls is
min(m, n) + 1, wheremis the initial length ofs1andnis the initial length ofs2.For example, if
s1 = "abc"ands2 = "de"it will take 2 recursive calls to traverses2(the string with the minimum length) plus one extra call for exiting at the base case, thereforemin(s1.length(), s2.length()) + 1 == 3. You can test it programmatically like this:Now when you run the following statements, the formula works as expected: