Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion To understand recursion, you first have to understand recursion.

Similar presentations


Presentation on theme: "Recursion To understand recursion, you first have to understand recursion."— Presentation transcript:

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

10

11

12

13

14

15

16

17

18

19

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…


Download ppt "Recursion To understand recursion, you first have to understand recursion."

Similar presentations


Ads by Google