Open YuezhenQin opened 11 months ago
The opposite of a recursive algorithm would be an iterative algorithm. There is a branch of study that proves that any iterative algorithm can be written recursively. While iterative algorithms use for
loops and while
loops to simulate repetition, recursive algorithms use function calls
to simulate the same logic.
function fn(i):
if i > 3:
return
print(i)
fn(i + 1)
print(f"End of call where i = {i}")
return
fn(1)
If you ran this code, you would see the following in the output:
// 1 // 2 // 3 // End of call where i = 3 // End of call where i = 2 // End of call where i = 1
As you can see, the line where we print text is executed in reverse order. The original call fn(1) first prints 1, then calls to fn(2), which prints 2, then calls to fn(3), which prints 3, then calls to fn(4). Now, this is the important part: how recursion "moves" back "up". fn(4) triggers the base case
, which returns. We are now back in the function call where i = 3 and line 4 has finished, so we move to the line 5 which prints "End of call where i = 3". Once that line runs, we move to the next line, which is a return. Now, we are back in the function call where i = 2 and line 4 line has finished, so again we move to the next line and print "End of the call where i = 2". This repeats until the original function call to fn(1) returns.
This printing example is pretty pointless - it's easier to use a for loop if you just want to print numbers. Where recursion shines is when you use it to break down a problem into "subproblems", whose solutions can then be combined to solve the original problem.
Recursion is a problem solving method. In code, recursion is implemented using a function that calls itself. Each function call stores its own variables, as the solution of a problem, pass it to build up a solution of the actual size of the problem.
We need what is called a
base case
to make the recursion stop. The base cases are conditions at the start of recursive functions that terminate the calls.We also need what is called a
recurrence relation
- it's an equation that connects the terms together.By combining the base cases and the recurrence relation, we can solve the subproblems and use those solutions to solve the original problem.