🎉 Nextra 4.0 is released. Read more →

Recursive Algorithm

Boon Wee Toh,

Recursive Algorithm

As recursion is the process of defining a problem/solution in terms of a simpler version of itself, a recursive algorithm is an algorithm that calls itself with simpler parameters.

Recursion comes directly from Mathematics, where there are many examples of expressions written in terms of themselves. A well-known example is the Fibonacci sequence as defined:

F(i) = F(i-1) + F(i-2)

Before we start, we need to learn about the 3 laws of recursion. These 3 laws apply to all recursive algorithms, without any of the 3 laws it is not considered a recursive algorithm.

  1. Must have a base case (aka terminating condition)
  2. Must change its state and move towards the base case
  3. Must call itself recursively

Let’s use the Fibonacci sequence example and write a recursive algorithm.

https://miro.medium.com/max/456/1*jrFhZ4yV1oPbij296uewJA.jpeg

Code snippet of fibonacci function in Typescript

The code snippet was written in Typescript. It is a function that takes a number as an input, and outputs a number.

As mentioned, the 3 laws of recursion applies to this function.

  1. Must have a base case; if (n ≤ 1)
  2. Must change its state and move towards base case; return fibonacci(n-1) + fibonacci(n-2);
  3. Must call itself recursively; return fibonacci(n-1) + fibonacci(n-2);

Given the algorithm above, let’s see if we can figure out what F(5) equates to. I’ve created a diagram to help you visualize and work on it.

https://miro.medium.com/max/700/1*VsyQvhSUy7eQOTGb2clncw.jpeg

If you were able to work it out, you should arrive at the answer 5.

If not, here are the steps.

https://miro.medium.com/max/700/1*f_xr1FzZyXdmFsFaVIH33w.jpeg

If you’d like to try out some other inputs, here’s a cheat sheet for you to check your answer against.

https://miro.medium.com/max/700/1*EgY3swEOm7H8LUlYPYS1VQ.jpeg

Do note that all recursive functions can be converted to iterative functions and vice versa. So why use recursive functions instead of iterative functions? We’ll talk about that in the next post.

CC BY-NC 4.0 2025 © Dimitri POSTOLOV.RSS