Download presentation
Presentation is loading. Please wait.
Published byMalcolm Cox Modified over 8 years ago
1
Recursion To understand recursion, you first have to understand recursion
2
Recursion Recursion : Defining a problem's solution in terms of itself
3
Recursion Factorial: 5! = 5 x 4 x 3 x 2 x 1
4
Recursion Factorial: 5! = 5 x 4 x 3 x 2 x 1
5
Base Case Recursion involves – Base case No recursion Ending point – General case Do step n in terms of earlier steps factorial(n) = n * factorial(n-1) factorial(0) = 1
6
Recursion Factorial: fact(5) = 5 x fact(4) fact(5) = 5 x (4 x fact(3)) fact(5) = 5 x (4 x (3 x fact(2))) fact(5) = 5 x (4 x (3 x (2 x fact(1)))) fact(5) = 5 x (4 x (3 x (2 x (1 x fact(0))))) fact(5) = 5 x (4 x (3 x (2 x (1 x (1))))) factorial(n) = n * factorial(n-1) factorial(0) = 1
7
Recursion Implemented In code: – Always an if Base case : End recursion General case : Do something, make recursive call
8
Recursion Recursive call is divider – Instructions before happen as stack is built – Instructions after happen as stack torn down
9
Trace Recursive factorial
20
Recursion vs Iteration Recursion is an alternative to iteration – Can always replace one with the other
21
Why Recursion??? Times when essential: – Functional Programming Times when elegant: – Divide & Conquer Sorts – Searches Towers of Hanoi TicTacToe
22
Towers Of Hanoi 3 Pegs & Stack of disks – Get from one peg to another – Can only move one disk at a time – Big disks can not be on top of small disks
23
Towers Of Hanoi 3 disks = 7 moves N disks = 2 n – 1 moves
24
Tic Tac Toe Min Max Search – Try every move, with each Have opponent try every move left over, then – You try every move still left…
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.