Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything which can only be achieved by recursion?

I am not sure but I had heard of an algorithm which can only be achieved by recursion. Does anyone know of such thing?

like image 589
Shubham Avatar asked Nov 28 '22 12:11

Shubham


2 Answers

You can always simulate recursion by keeping your own stack. So no.

like image 127
sepp2k Avatar answered Jan 01 '23 20:01

sepp2k


You need to clarify what kind of recursion you are talking about. There's algorithmic recursion and there's recursion in the implementation. It is true that any recursive algorithm allows for a straightforward non-recursive implementation - one can easily do it by using the standard trick of simulating the recursion with manual stack.

However, your question mentions algorithms only. If one assumes that it is specifically about algorithmic recursion, then the answer is yes, there are algorithms that are inherently and unavoidably recursive. In general case it is not possible to replace an inherently recursive algorithm with a non-recursive one. The simplest way to build an inherently recursive algorithm is to take an inherently recursive data structure first. For example, let's say we need to traverse a tree with only parent-to-child links (and no child-to-parent links). It is impossible to come up with a reasonable non-recursive algorithm to solve this problem.

So, that's one example for you: traversal of a tree, which has only parent-to-child links cannot be performed by a non-recursive algorithm.

Another example of an inherently recursive algorithm is the well-known QuickSort algorithm. QuickSort is always recursive, and it cannot be turned into a non-recursive algorithm simply because if you succeed in doing this it will no longer be QuickSort anymore. It will be a completely different algorithm. Granted, this sounds as an exercise in pure semantics, but nevertheless that's also something that is worth mentioning.

like image 44
AnT Avatar answered Jan 01 '23 20:01

AnT