Recursion To understand recursion, you first have to understand recursion
Recursion Recursion : Defining a problem's solution in terms of itself
Recursion Factorial: 5! = 5 x 4 x 3 x 2 x 1
Recursion Factorial: 5! = 5 x 4 x 3 x 2 x 1
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
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
Recursion Implemented In code: – Always an if Base case : End recursion General case : Do something, make recursive call
Recursion Recursive call is divider – Instructions before happen as stack is built – Instructions after happen as stack torn down
Trace Recursive factorial
Recursion vs Iteration Recursion is an alternative to iteration – Can always replace one with the other
Why Recursion??? Times when essential: – Functional Programming Times when elegant: – Divide & Conquer Sorts – Searches Towers of Hanoi TicTacToe
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
Towers Of Hanoi 3 disks = 7 moves N disks = 2 n – 1 moves
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…