Page 4
Recursive Algorithms
Page 5
Example: Gift box!
Page 6
Example: Gift box!
Page 7
Example: Gift box!
Page 8
Value of gift box : Equation?
Page 9
Example: Treasure hunt!
Page 10
What is recursion?
• Popular in math definitions• Inductive proof
Page 11
Example: factorial(n)
Page 12
Example: factorial(n)
• Non-recursive solution
Page 13
How does recursion work?
• Stack memory• How much stack memory is needed?
Page 14
How to understand recursion?
• Method invocations & returns diagram• Example: factorial(5)
Page 15
How to understand recursion?
• Method invocations & returns diagram• Example: fibonacci(n)
Page 16
How to understand recursion?
• Tree diagram• Example: fibonacci(n)
Page 17
fibonacci(n) : non-recursive solution?
Page 18
How to analyze recursion?
• Recurrence relation & Time complexity
Page 19
Example: Hanoi tower
Page 20
Example: FractalsVon_Koch_curve.gif
Page 21
Petrol cost minimization problem
Page 22
Similar solution: Quick-sort
Page 23
Quick-sort: non-recursive solution?
Page 24
Similar solution: Merge-sort
Page 25
Example: Knapsack problem
Page 26
Example: Change for $ 100
• Available denominations: 1c, 5c, 10c, 25c, $1, $2, $5, $10, $20, $50, $100
• How many combinations are there?
Page 27
How to make recursion efficient?
• Parameters• Tail recursion
Page 28
Example: N-Queens puzzle
Page 29
Example: Knight’s tour
Page 30
Example: Sudoku’s puzzle
Page 31
Example: Maximizing total conviviality
Page 32
Conclusions• Recursion is one of the difficult concepts to
understand, perhaps it is not that intuitive.• As per a few mathematicians & CS folks, it is
one of the most beautiful concepts!• While it is not used much in commercial
applications, it certainly puts your logical thinking skills to work!
• It is easy to remove tail recursion, but all others are lot harder to remove.
Page 33
Questions & Answers?