Recursion - The beginning
Premise:- When we start with algorithms, recursion remains a major bottleneck in understanding complex algorithms. This discussion intends to provide motivation in learning, and providing steps on visualising mental model.
What is Recursion:- The best way to understand is to go through the wiki recursion.
In short, when a function/set of funtions calls itself from itself with some change in parameters is called recursion.
Its used it a variety of places, interesting ones are below:
Simplest example of recursion(with Java):-
public class Recursion {
public static void main(String args[])
{
System.out.println("main");
main(null);
}
}
Output:-
If we see the line number above,"main" was printed around 11764(this can be different in your computer as it depends on the stack size) times and then we get stackOverFlowError.
Now the question arises "From where did the stack come from" ?
There are 2 kinds of memory allocated by JVM. The Stack and the Heap. Memory is allocated to Stack when local methods or primitive variables are executed. Memory to heap is allocated when objects are created. They are described as below.
So, basically, For every call to the same method, memory is allocated in the stack and the control goes from the top of the stack by popping out the executed method and returning the corresponding value to the next in the stack.
The following problems should be a good start to getting recursion:-
- Print numbers from 1 to 100 using recursion. Hint: use a Heap variable.
- Find prime numbers between n1 and n2 using recursion. Hint:Try to make a mental model of converting solution of loops to recursion
- Find factorial using recursion. Hint: return statement is what matters :)
... recursion- to be continued
Please let me know your comments regarding the article below, Also and for more discussion regarding data structures and algorithms and please join our free forum at https://discord.gg/4M5dr3E
According to me sir, recursion is a very good as a mathematical representation. But implementation wise they aren't fast enough. I would love see an article on dynamic programming.