Base case in recursive method

The theoretical question here is about the case of a base or stop in a recursive method, what are its standards?

I mean, is it normal that there is no body in it, just an expression of return?

It's always like that:

if (input operation value) return sth; 

Do you have different thoughts about this?

+7
recursion
source share
4 answers

The pattern for recursive functions is that they look something like this:

 f( value ) if ( test value ) return value else return f( simplify value ) 

I do not think that you can say much more than about general cases.

+7
source share

The main case is to end the loop (avoid infinite recursion). In the basic case, there is no standard; any input that is simple enough so that it can be precisely solved can be chosen as one.

For example, this is perfectly true:

 int factorial (int n) { if (n <= 5) { // Not just a return statement int x = 1; while (n > 0) { x *= n; -- n; } return x; } else { return n * factorial(n-1); } } 
+1
source share

In some cases, your base case

 return literal 

In some cases, your base case is not just “returning a literal”.

It cannot be "standard" - it depends on your function.

The Syracuse function http://en.wikipedia.org/wiki/Collatz_conjecture , for example, does not have a trivial base case or trivial literal.

"Do you have different thoughts about this?" This is actually not a reasonable question.

Recursion should end with that. Trivial tail recursion can have a "base case" that returns a literal, or it can be a calculation. More complex recursion may not have the trivial “base case”.

+1
source share

It completely depends on the particular recursive function. In general, this cannot be an empty return; although - for any recursive function that returns a value, the base register should also return a value of this type, since func(base) also a perfectly valid call. For example, the recursive factorial function returns 1 as the base value.

0
source share

All Articles