Why the Heck Do We Need Recursion?

Recursion is inefficient. But sometimes it makes things easy

Amrit Pal Singh
CodeHeim
2 min readMar 17, 2022

--

Photo by Natalya Letunova on Unsplash

We all learn to solve programming problems recursively just to realize later that it is an inefficient way to implement. Any recursive algorithm can be implemented in an iterative fashion.

The iterative version of an algorithm is always more efficient than the recursive one. Then why do we need to learn recursion?

Recursive nature of a problem

Sometimes the problem is recursive in nature. Quicksort, BST traversal, Depth-first search, Breadth-first search, etc. are a few examples of such problems.

Most of the divide and conquer algorithms are easy to implement with recursion. Of course, these can be implemented iteratively. The iterative method would definitely give you better performance but recursion is easy to implement for such algorithms.

Code readability

One of the most important aspects of good code is its readability. There is no doubt that iterative implementation might perform better but recursion makes the code easy.

Recursion uses the same code by calling itself. This makes the implementation easy, readable, and maintainable. Let’s look at the example of Quicksort —

This is the recursive Python implementation of Quicksort —

Recursive implementation

And the iterative implementation looks like this —

Iterative implementation

As you can see, recursion makes the code easy and readable for problems that are recursive in nature. In such scenarios, you need to take a call. It’s efficiency vs readability.

Wrapping it up

Recursion is an important concept for a programmer to learn. It feels very unusual in the beginning. But as soon as you get a hang of it, it is simple to use.

While solving a problem that is recursive in nature, it is a call of the programmer to use recursion or iterative method.

Like to experience Medium yourself? Consider supporting me and other writers by signing up for a membership. Membership is only $5 per month, it supports us, writers, at no extra cost. If you do so, I receive a portion of the fee, and it won’t cost you more. Thank you!

--

--

Amrit Pal Singh
CodeHeim

Cloud Software Engineer | Product Development | I write about Tech and Travel | Profile https://bit.ly/3dNxaiK | Golang Web Dev Course - https://bit.ly/go-gin