Recursion
Santiago Neira
Software Developer | Estudiante Analista en TecnologÃas de la Información | Javascript | ReactJS | NextJS | NodeJS | SQL | AWS
First, what is it?
Recursion is a broad concept, complicated to think about, although we can see it in daily activities and, being aware of that, understand it more and more, for example, a photo of a photo, a live broadcast into a live broadcast among other situations.
A good example is that you imagine yourself waiting in a supermarket queue and you want to know how many people are in front of you without getting out of line and counting them, you can ask the person in front of you until someone knows how to answer and the answer comes back to you.
The concept we want to reach is programming-focused recursion: it allows defining an object (problems, data structures) in terms of itself.
Some problems defined recursively are the factorial of a number, the Fibonacci series, etc.
to remember the factorial of a number is the product of all the natural numbers before it.
in code:
Solving a problem using recursion means that the solution depends on the solutions of small instances of the same problem.
The key points to developing a recursive function are:
领英推è
1- Each recursive call (to the same function) must define a less complex problem.
2 -There must be at least one base case or final condition (or it will be infinite).
if we identify this in the case of the factorial number the base case of the function is when we get to 0 without this condition the function would call itself infinitely.
Why use recursion and why not?
The first clear advantage is the elegance that it offers in the face of the complexity of a problem, that is, it reduces a complex problem to three or four lines of code.
The main advantages of recursion are optimization and reducing time complexity.
and drawbacks related to memory usage, as the number of method invocations in your computer's memory increases, you may run out of memory.
Now, another bad point, just like any piece of code, is that if recursion is overused, you can get this kind of habit where you start developing really complex code that is hard for outsiders to understand.
The questions we should ask ourselves to avoid this are:
- Is this a good use case?
- Can I really break it down into subproblems that make sense for recursion?
If it can't, we need to identify when we have unnecessarily complex code.
I hope I was able to be clear with the explanation of this concept, thanks for reading :)