Cs212: DataStructures

26
CS212: DATASTRUCTURES Lecture 4: Recursion 1

description

Cs212: DataStructures. Lecture 4: Recursion. Lecture Contents. The Concept of Recursion Why recursion ? Factorial – A case study Content of a Recursive Method Recursion vs. iteration. The Concept of Recursion. - PowerPoint PPT Presentation

Transcript of Cs212: DataStructures

Page 1: Cs212:  DataStructures

CS212: DATASTRUCTURES

Lecture 4: Recursion

1

Page 2: Cs212:  DataStructures

2

Lecture Contents

The Concept of Recursion Why recursion? Factorial – A case study Content of a Recursive Method Recursion vs. iteration

Page 3: Cs212:  DataStructures

3

The Concept of Recursion

repetition can be achieved by writing loops, such as for loops and while loops.

Another way to achieve repetition is through recursion, which occurs when a function calls itself.

A recursive function is a function that calls itself , either directly or indirectly ( through another function).

For example :void myFunction( int counter)

{if(counter == 0)     return;else       {             myFunction(--counter);       return;       }

}

Page 4: Cs212:  DataStructures

4

Why recursion?

Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first

Recursion is a technique that solves a problem by solving a smaller problem of the same type

Allows very simple programs for very complex problems

Page 5: Cs212:  DataStructures

5

Factorial – A case study

Factorial definition: the factorial of a number is product of the integral values from 1 to the number.

factorial 3

3*2*1=

6=

Page 6: Cs212:  DataStructures

6

Factorial – A case study

Iteration algorithm definition (non-recursive)

factorial 4

product [4..1]=

product [4,3,2,1]=

4*3*2*1=

24=

1 if n = 0 Factorial(n) =

n*(n-1)*(n-2)*…*3*2*1 if n > 0

Page 7: Cs212:  DataStructures

Factorial – A case study

Recursion algorithm definition

7

factorial 3

3 * factorial 2=

3 * (2 * factorial 1)=

3 * (2 * (1 * factorial 0))

=

3 * (2 * (1 * 1))=

3 * (2 * 1)=

=

6

3 * 2=

1 if n = 0 Factorial(n) =

n * ( Factorial(n-1) ) if n > 0

7

Page 8: Cs212:  DataStructures

8

Content of a Recursive Method

Base case(s). One or more stopping conditions that can be directly

evaluated for certain arguments there should be at least one base case.

Recursive calls. One or more recursive steps, in which a current value of

the method can be computed by repeated calling of the method with arguments (general case).

The recursive procedure call must use a different argument that the original one: otherwise the procedure would always get into an infinite loop…

Page 9: Cs212:  DataStructures

9

Content of a Recursive Method

void myFunction( int counter){if( counter == 0)     …........else {      ………       myFunction(--counter);

  }}

Use an if-else statement to distinguish between a Base case

and a recursive step

Page 10: Cs212:  DataStructures

10

Iterative factorial algorithm

public static int recursiveFactoria(int n) {

i = 1

factN = 1

for(int i=1; i<= n; i++)

factN = factN * i

i = i + 1

return factN

}

public static int recursiveFactoria(int n) {

if (n == 0)return 1; // base case

else return n * recursiveFactorial(n-1): // recursive case

}

Recursive factorial Algorithm

recursive implementation of the factorial function is somewhat simpler than the iterative version in this case there is no compelling reason for preferring recursion over iteration. For some problems, however, a recursive implementation can be significantly simpler and easier to understand than an iterative implementation.

Page 11: Cs212:  DataStructures

11

Tracing Recursive Method

• Each recursive call is made with a new arguments Previous calls are suspended

• Each entry of the trace corresponds to a recursive call.

• Each new recursive function call is indicated by an arrow to the newly called function.

• When the function returns, an arrow showing this return is drawn and the return value may be indicated with this arrow.

Page 12: Cs212:  DataStructures

12

Recursion vs. iteration

Iteration can be used in place of recursion An iterative algorithm uses a looping

construct A recursive algorithm uses a branching

structure(if-statement) Recursive solutions are often less

efficient, in terms of both time and space, than iterative solutions

Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code

Page 13: Cs212:  DataStructures

13

Recursion

1 Linear Recursion

2 Binary Recursion

3 Multiple Recursion

Page 14: Cs212:  DataStructures

14

1 Linear Recursion

The simplest form of recursion is linear recursion, where a method is defined so that it makes at most one recursive call each time it is invoked.

Page 15: Cs212:  DataStructures

15

Summing the Elements of an Array Recursively

Algorithm LinearSum(A , n )input A integer array A and an

integer n>=1, such that A has at least n elements

output The sum of the first n

integers in A

if (n = 1) then return A[0]else return LinearSum(A, n - 1) +

A[n - 1]

4 3 6 2 5A =

n = 5

Page 16: Cs212:  DataStructures

16

Summation (Sigma) NotationAlgorithm sum ( n <integer>)Input

n is an integer number

o

is returned if (n == 1) return 1;else return n + sum(n-1);End IF

Page 17: Cs212:  DataStructures

17

Summation (Sigma) Notation con..

Sum (3)return 3+Sum(2)return 3+3 Sum(2)

return 2+ sum(1) return 2+1

Sum(1) return 1

return 1

return 3

return 6

For n =3

Page 18: Cs212:  DataStructures

18

Printing “Hello World” n Times Using Recursion

Algorithm printHelloWorld ( n <integer>)Input

n is an integer numberOutput

“Hello World” printed n times

If ( n >0 ) {

Print “Hello World”

printHelloWorld( n – 1 );

}

Page 19: Cs212:  DataStructures

19

Printing “Hello World” n Times Using Recursion

printHelloWorld(3)Print hello worldprintHelloWorld(2)

hello world

printHelloWorld(2)Print hello worldprintHelloWorld(1)

hello world

printHelloWorld(1)Print hello world printHelloWorld(0)

hello world

printHelloWorld(0)

return

return

return

return

Page 20: Cs212:  DataStructures

20

2 Binary Recursion

When an algorithm makes two recursive calls, we say that it uses binary recursion. These calls can, for example, be used to solve two similar halves of some problem,

Page 21: Cs212:  DataStructures

21

Computing Fibonacci Numbers via Binary Recursion

Let us consider the problem of computing the kth Fibonacci number.

{0, 1, 1, 2, 3, 5, 8, 13, 21, 34,….} Fibonacci numbers are recursively defined

as follows: F0 = 1 F1 = 1 Fi = Fi−1 + Fi−2.

Page 22: Cs212:  DataStructures

22

Computing Fibonacci Numbers con..

Algorithm BinaryFib(k):Input:

Nonnegative integer k

Output: The kth Fibonacci number f

if (k< I) then return kelsereturn BinaryFib(k - 1) + BinaryFib(k -2)

Page 23: Cs212:  DataStructures

23

Calculate BinaryFib(3)

Page 24: Cs212:  DataStructures

24

Exercise

what is the output of fun(16)?

Algorithm fun(int X)

if ( x <=4 ) return 1

elsereturn fun(x/4) + fun (x/2)

Result = 3

Page 25: Cs212:  DataStructures

25

3 Multiple Recursion

Generalizing from binary recursion, we use multiple recursion when a method may make multiple recursive calls, with that number potentially being more than two.

Page 26: Cs212:  DataStructures

26 End Of Chapter