Recursion
reading: Dietel sections 3.12-3.14
any self-referential definition or process
data structures can also be recursive (self-referential)
can use recursive functions to solve self-similar problems
Finding the Maximum Number
we have a list of numbers
want to find the maximum
the maximum is the larger of:
the first element or the maximum out of the rest of the elements
we can write a recursive solution to this self-similar problem
note that if there is only one number, that number is the maximum
Recursive Algorithm
int Maximum( int Array[], int size, int start_position)
{
int recursive_max;
if( size == start_position + 1) // Only one element
return Array[start_position];
recursive_max = Maximum(Array, size, start_position+1); // Maximum of rest of array
if( Array[start_position] > recursive_max)
return Array[start_position];
else
return recursive_max;
}
How does this work?
recursive calls work just like regular function calls
when a recursive call is made, all local variables are saved on the call stack
when the recursive call returns, the calling function proceeds as normally
we can trace the function's behavior
Recognizing and Solving Recursive Problems
Can we break the problem down into smaller versions of itself?
determines the form of the recursive call
Maximum of n elements depends on Maximum of n-1 elements
Once the problem is small enough, can we solve it directly?
we can solve for the Maximum of a one-long list directly
this is called the base case -- ensures no infinite loops
If so, we can write a recursive solution.
Recursion vs. Iteration
We could have easily found the maximum number with a loop
Advantages of iteration:
faster since no overhead for function calls, stack management
size of problem not limited by size of stack
can be easier to trace program execution
Advantages of recursion:
some algorithms can be expressed more simply
some problems lend themselves to intuitive recursive solutions
Factorials, Fibonacci numbers, etc.