Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good example of recursion other than generating a Fibonacci sequence?

Possible Duplicates:
Real-world examples of recursion
Examples of Recursive functions

I see that most programming language tutorial teach recursion by using a simple example which is how to generate fibonacci sequence, my question is, is there another good example other than generating fibonacci sequence to explain how recursion works?

like image 258
uray Avatar asked Feb 09 '11 12:02

uray


People also ask

What is a good example of recursion?

A classic example of recursion For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .

What are the three types of recursion?

Different types of the recursionDirect Recursion. Indirect Recursion. Tail Recursion.

What are the two types of recursion give proper examples?

Recursion are mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. The first one is called direct recursion and another one is called indirect recursion.

Which types of problems can be solved using recursion?

Problems like finding Factorial of a number, Nth Fibonacci number and Length of a string can be solved using recursion.


2 Answers

The classic is the binary tree search:

def findval (node,val):     if node == null:         return null     if node.val = val:         return node     if node.val > val:         return findval (node.left,val)     return findval (node.right,val)  findval (root,thing_to_find) 

That may be a little more complex than a simple formula but it's the "bread and butter" use of recursion, and it illustrates the best places to use it, that where the recursion levels are minimised.

By that I mean: you could add two non-negative numbers with:

def add (a,b):     if b == 0:         return a     return add (a+1,b-1) 

but you'd find yourself running out of stack space pretty quickly for large numbers (unless the compiler optimised tail-end recursions of course, but you should probably ignore that for the level of teaching you're concerned with).

like image 142
paxdiablo Avatar answered Sep 26 '22 02:09

paxdiablo


The other answers mention various algorithms, which is completely fine, but if you want a bit more "concrete" example, you could list all files in some directory and its subdirectories. The hierarchical file system is a well-known example of a recursive (tree) structure, and you could show depth-first and breadth-first search using this concrete example.

like image 37
Philipp Avatar answered Sep 27 '22 02:09

Philipp