Recursive Functions

Recursive functions call themselves
Make sure to write the base exit & Modify the input counter or you will shoot for infinity.

To read more about recursion here is a good blog post: LINK

Here is an example:

This function will print:

An that is a basic intro to recursion.

Now I read an article that says that you can create the Fibonacci sequence using Recursion.

Example of the Fibonacci sequence:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

and here is my code to generate recursive Fibonacci:

and here is the run time:


Latter I found a more compact solution in the internet:

This little code might seem better but is not, this has an exponential run time, my solution that has more code, actually has a much much better execution time.

here is the run-time for the same tests using the short code (Note I had to delete the call for fib 50 because would just take forever.):

Here are a couple of basic functions that use recursion:

Here is my take on the recursive solution to the Merge-Sort algorithm:

If you are new to recursive functions this might not make sense, but the real importance goes in the line with the code: return joinarr( myMerge(h1), myMerge(h2) )

Here is the complete code:



Copyright 2017. All rights reserved.

Posted January 2, 2018 by Edmundo in category "JS