Functions : Recursion Lecture 11 4.2.2002 1

Download Report

Transcript Functions : Recursion Lecture 11 4.2.2002 1

1

Functions : Recursion

Lecture 11 4.2.2002

31.1.2001

Sudeshna Sarkar, IIT Kharagpur

2

Announcements

 Class Test – I on 7 th February, 6pm  Section 1 & 2 at S-301  Section 5 & 6 at S-302 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

3

Call by value

} } void printDouble (int x) { printf (“Double of %d “, x); x *= 2; printf (“is %d\n”, x) ; void main () { int num=15; printDouble (num); printf (“ num = %d\n”, num); Note : The parameter of a function can be a constant, variable, expression – anything that has a value.

Only the value is passed to the function.

31.1.2001

Sudeshna Sarkar, IIT Kharagpur

4

Recursion

 Def : A function is recursive if it calls itself. int

rfun

(int x) { . . .

rfun

(2*a) ; . . .

}  Questions :  How does recursion work ?

 Why do I write a recursive function ?

31.1.2001

Sudeshna Sarkar, IIT Kharagpur

5

Thinking Recursively

Learning Objectives  To learn to think recursively    To learn how strategies for recursion involve both base cases and recursion cases To learn how to search for different ways of decomposing a problem into subproblems .

To understand how to use call trees and traces reason about how recursive programs work to 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

6

Program vs Process

 Program = a set of instructions  akin to the blueprint of an information factory  Process = activity performed by computer when obeying the instructions  akin to operation of a working factory  can create multiple factories as needed from the same blueprint  need to allocate different local variables 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

7

Factorial via Recursion

} /* 0! = 1! = 1, for n>1, n! = n* (n-1)! */ int

factorial

(int n) { int t; if (n <=1) t=1; else

t = n * factorial (n-1)

; return t; 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

8

Review : Function Basics

 Tracing recursive functions is apparent if you remember the basics about functions :  Formal parameters and variables declared in a function is local to it.

 Allocated (created) on function entry  De-allocated (destroyed) on function return  Formal parameters initialized by copying value of actual parameter.

31.1.2001

Sudeshna Sarkar, IIT Kharagpur

9

Factorial

factorial (4) = 4 * factorial (3) = 4 * 3 * factorial (2) = 4 * 3 * 2 * factorial (1) = 4 * 3 * 2 * 1 = 24 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Factorial Trace

n t t t n t 10 31.1.2001

t n Sudeshna Sarkar, IIT Kharagpur

11 } { int findmax (int n) int i, num, max; scanf ("%d", &num) ; max = num; for (i=1; i max) max = num; } return max; 31.1.2001

int findmax (int n, int max) { int num; if (n==0) return max; scanf ("%d", &num) ; if (num > max) max = num; max = findmax (n-1, max) ; return max; } Sudeshna Sarkar, IIT Kharagpur

Iteration vs. Recursion

 Any iterative algorithm can be re-worked to use recursion, and vice-versa.

 Some algorithms are more naturally written with recursion.

 But naive applications of recursion can be inefficient.

12 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

When to use Recursion ?

 Problem has 1 or more simple cases.

 These have a straightforward non-recursive solution.

 Other cases can be re-defined in terms of problems that are closer to simple cases  By applying this redefn process repeatedly one gets to one of the simple cases.

13 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Example

int sumSquares (int m, int n) { int i, sum; } sum = 0; for (i=m; i<=n; i++) sum += i*i; return sum; 14 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Example

int sumSquares (int m, int n) { if (m

} int sumSquares (int m, int n) { if (m

Example

} int sumSquares (int m, int n) int middle ; if (m==n) return m*m ; { 5 . . .

else { middle = (m+n)/2; m return sumSquares(m,middle) 7 8 . . .

mid mid+1 + sumSquares(middle+ 1,n) ; 10 n 16 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Call Tree

sumSquares(5,7) sumSquares(5,6) sumSquares(7,7) sumSquares(8,9) sumSquares(10,10) sumSquares(5,5) sumSquares(6,6) sumSquares(8,8) sumSquares(9,9) 17 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Annotated Call Tree

355 61 sumSquares(5,6) 110 sumSquares(5,7) 245 49 sumSquares(7,7) 145 sumSquares(8,9) 100 sumSquares(10,10) 25 sumSquares(5,5) 36 sumSquares(6,6) 64 sumSquares(8,8) 81 sumSquares(9,9) 18 25 36 49 64 31.1.2001

81 100 Sudeshna Sarkar, IIT Kharagpur

Trace

sumSq(5,10) = (sumSq(5,7) + sumSq(8,10)) = (sumSq(5,6) + (sumSq(7,7)) + (sumSq(8,9) + sumSq(10,10)) = ((sumSq(5,5) + sumSq(6,6)) + sumSq(7,7)) + ((sumSq(8,8) + sumSq(9,9)) + sumSq(10,10)) = ((25 + 36) + 49) + ((64 + 81) + 100) = (61 + 49) + (145 + 100) = (110 + 245) = 355 19 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

20

Recursion : The general idea

 Recursive programs are programs that call themselves  to compute the solution to a subproblem having these properties : 1. the subproblem is smaller than the overall problem or, simpler in the sense that it is closer to the final solution 2. the subproblem can be solved directly or recursively (as a base case) by making a recursive call.

3. the subproblem’s solution can be combined with solutions to other subproblems to obtain the solution to the overall problem.

31.1.2001

Sudeshna Sarkar, IIT Kharagpur

21

Think recursively

 Break a big problem into smaller subproblems of the same kind, that can be combined back into the overall solution : Divide and Conquer 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

22

Exercise

1. Write a recursive function that computes

x n

, called

power (x, n

), where x is a floating point number and n is a non negative integer.

2. Write an improved recursive version of

power(x,n)

that works by breaking n down into halves, squaring

power(x, n/2),

and multiplying by x again if n is odd.

3. To calculate the square root of x (a +ve real) by Newton’s method, we start with an initial approximation a=x/2 . If |x a  a|  epsilon , we stop with the result a. Otherwise a is replaced with the next approximation, (a+x/a)/2 . Write a recursive method,

sqrt(x)

Newton’s method.

to compute square root of x by 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

23

Common Pitfalls

 Infinite Regress : a base case is never encountered   a base case that never gets called : fact (0) running out of resources : int fact (int n) { if (n==1) return 1; return n*fact(n-1); } each time a function is called, some space is allocated to store the activation record. With too many nested calls, there may be a problem of space.

31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Tower of Hanoi

24 A B 31.1.2001

C Sudeshna Sarkar, IIT Kharagpur

Tower of Hanoi

25 A B 31.1.2001

C Sudeshna Sarkar, IIT Kharagpur

Tower of Hanoi

26 A B 31.1.2001

C Sudeshna Sarkar, IIT Kharagpur

Tower of Hanoi

27 A B 31.1.2001

C Sudeshna Sarkar, IIT Kharagpur

28 void towers (int n, char from, char to, char aux) { if (n==1) { printf (“Disk 1 : %c -> &c \n”, from, to) ; return ; } towers (n-1, from, aux, to) ; printf (“Disk %d : %c  %c\n”, n, from, to) ; towers (n-1, aux, to, from) ; } 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

29 Disk 1 : A -> C Disk 2 : A -> B Disk 1 : C -> B Disk 3 : A -> C Disk 1 : B -> A Disk 2 : B -> C Disk 1 : A -> C Disk 4 : A -> B Disk 1 : C -> B Disk 2 : C -> A Disk 1 : B -> A Disk 3 : C -> B Disk 1 : A -> C Disk 2 : A -> B Disk 1 : C -> B towers (4, ‘A’, ‘B’, ‘C’) ; 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Recursion may be expensive !

30  Fibonacci Sequence:  fib (n) = n if n is 0 or 1  fib (n) = fib (n-2) + fib(n-1) if n>= 2.

int fib (int n) if (n==0 or n==1) return 1; { return fib(n-2) + fib(n-1) ; } 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Call Tree

31 2 fib (3) 1 fib (1) 1 0 fib (0) 0 1 fib (2) 1 fib (1) 1 5 fib (5) 0 fib (0) fib (1) 0 1 fib (2) 3 fib (4) 1 1 2 fib (3) 1 fib (1) 1 0 fib (0) 1 fib (2) 1 fib (1) 0 1 31.1.2001

Sudeshna Sarkar, IIT Kharagpur

Iterative fibonacci computation

32 int fib (int n) { if (n <= 1) return n; lofib = 0 ; hifib = 1 ; for (i=2; i<=n; i++) { x = lofib ; lofib = hifib ; hifib = x + lofib; } return hifib ; } 31.1.2001

i = 2 3 4 5 6 7 x = 0 1 1 2 3 5 lofib= 0 1 1 2 3 5 8 hifib= 1 1 2 3 5 8 13 Sudeshna Sarkar, IIT Kharagpur

33

Merge Sort

 To sort an array of N elements,  1. Divide the array into two halves. Sort each half.

 2. Combine the two sorted subarrays into a single sorted array  Base Case ?

31.1.2001

Sudeshna Sarkar, IIT Kharagpur

34

Binary Search revisited

 To search if key occurs in an array A (size N) sorted in ascending order:  mid = N/2;  if (key == N/2) item has been found  if (key < N/2) search for the key in A[0..mid-1]  if (key > N/2) search for key in A[mid+1..N]  Base Case ?

31.1.2001

Sudeshna Sarkar, IIT Kharagpur