Docsity

Recursion Lecture Notes for CS2110 Summer 2008, Assignments of Computer Science

Toggle sidebar
bg1
1
Recursion
Lecture 3
CS2110 – Summer 2008
2
Announcements
yFor extra Java help
Lots of consulting/office-hours available
Can set up individual meetings with TAs via email
yCheck soon that you are in CMS
yAcademic Integrity Note
Assignment #1 must be done individually
We treat AI violations seriously
The AI hearing process is unpleasant
Please help us avoid this process by maintaining Academ ic
Integrity
We test all pairs of submitted programming assignments for
similarity
Similarities are caught even if variables are renamed
4
Recursion Overview
yRecursion is a powerful technique for specifying
functions, sets, and programs
yExample recursively-defined functions and programs
factorial
combinations
exponentiation (raising to an integer power)
yExample recursively-defined sets
grammars
expressions
data structures (lists, trees, ...)
5
The Factorial Function (n!)
yDefine n! = n·(n−1)·(n−2)···3·2·1 read: “n factorial”
E.g., 3! = 3·2·1 = 6
yBy convention, 0! = 1
yThe function int →int that gives n! on input n is called
the factorial function
yn! is the number of permutations of n distinct objects
There is just one permutation of one object. 1! = 1
There are two permutations of two objects: 2! = 2
1 2 2 1
There are six permutations of three objects: 3! = 6
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
yIf n > 0, n! = n·(n −1)!
6
A Recursive Program
static int fact(int n) {
if (n = = 0) return 1;
else return n*fact(n-1);
}
0! = 1
n! = n·(n−1)!, n > 0
1
1
2
6
Execution of fact(4)
fact(1)
fact(4)
fact(3)
fact(0)
fact(2)
24
7
General Approach to Writing
Recursive Functions
1. Try to find a parameter, say n, such that the solution
for n can be obtained by combining s olutions to the
same problem using smaller values of n (e.g., (n-1)!)
2. Find base case(s) – small values of n for which you
can just write down the solution (e.g., 0! = 1)
3. Verify that, for any valid value of n, applying the
reduction of step 1 repeatedly will ultimately hit one
of the base cases
pf3
pf4
pf5

Partial preview of the text

Download Recursion Lecture Notes for CS2110 Summer 2008 and more Assignments Computer Science in PDF only on Docsity!

1

Recursion

Lecture 3 CS2110 – Summer 2008

2

Announcements

y For extra Java help

ƒ Lots of consulting/office-hours available ƒ Can set up individual meetings with TAs via email

y Check soon that you are in CMS

y Academic Integrity Note

ƒ Assignment #1 must be done individually ƒ We treat AI violations seriously ƒ The AI hearing process is unpleasant Š Please help us avoid this process by maintaining Academic Integrity ƒ We test all pairs of submitted programming assignments for similarity Š Similarities are caught even if variables are renamed

4

Recursion Overview

y Recursion is a powerful technique for specifying

functions, sets, and programs

y Example recursively-defined functions and programs

ƒ factorial ƒ combinations ƒ exponentiation (raising to an integer power)

y Example recursively-defined sets

ƒ grammars ƒ expressions ƒ data structures (lists, trees, ...) 5

The Factorial Function (n!)

y Define n! = n·(n−1)·(n−2)···3·2·1 read: “n factorial”

ƒ E.g., 3! = 3·2·1 = 6

y By convention, 0! = 1

y The function int → int that gives n! on input n is called

the factorial function

y n! is the number of permutations of n distinct objects

ƒ There is just one permutation of one object. 1! = 1 ƒ There are two permutations of two objects: 2! = 2 1 2 2 1 ƒ There are six permutations of three objects: 3! = 6 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1

y If n > 0, n! = n·(n − 1)!

A Recursive Program

static int fact(int n) {

if (n = = 0) return 1;

else return n*fact(n-1);

n! = n·(n−1)!, n > 0

Execution of fact(4)

fact(1)

fact(4)

fact(3)

fact(0)

fact(2)

General Approach to Writing Recursive Functions

1. Try to find a parameter, say n, such that the solution

for n can be obtained by combining solutions to the

same problem using smaller values of n (e.g., (n-1)!)

2. Find base case(s) – small values of n for which you

can just write down the solution (e.g., 0! = 1)

3. Verify that, for any valid value of n, applying the

reduction of step 1 repeatedly will ultimately hit one

of the base cases

8

The Fibonacci Function

y Mathematical definition: fib(0) = 0 fib(1) = 1 fib(n) = fib(n − 1) + fib(n − 2), n ≥ 2

y Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, …

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

two base cases!

Fibonacci (Leonardo Pisano) 1170−1240?

Statue in Pisa, Italy Giovanni Paganucci 1863

9

Recursive Execution

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

fib(4)

fib(3) fib(2)

fib(1) fib(0)

fib(2) fib(1) fib(1) fib(0)

Execution of fib(4):

10

Recursive vs. iterative solution

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

Static int iterative_fib(int n) { if (n == 1 || n == 2) return 1; int last_num = 1, result = 1; for (int i = 2; i < n; i++) { int temp = result; result += last_num; last_num = temp; } return result; }

11

Recursion Practice

// pre: s != null // post: returns list of all permutations of s static ArrayList permutations(String s);

/ Possibly useful functions /

// Deletes character at posn from s. // pre: s != null && 0 <= posn < s.length() // post: returns copy of s missing char at posn static String delete(String s, int posn);

// ArrayList methods void add(Object o); Object get(int posn); // String method char charAt(int posn);

12

Recursion Practice

// pre: s != null // post: returns list of all permutations of s static ArrayList permutations(String s) { ArrayList perms = new ArrayList(); if (s.length() <= 1) { perms.add(s); } else { for (int i = 0; i < s.length(); ++i) { char last = s.charAt(i); String rest = delete(s, i); ArrayList subperms = permutations(rest); for (int j = 0; j < subperms.length; ++j) { perms.add(subperms.get(j) + last); } } } return perms; }

13

Combinations

(a.k.a. Binomial Coefficients)

y How many ways can you choose r items from

a set of n distinct elements? ( ) “n choose r”

( ) = number of 2-element subsets of {A,B,C,D,E}

2-element subsets containing A: {A,B}, {A,C}, {A,D}, {A,E} 2-element subsets not containing A: {B,C},{B,D},{B,E},{C,D},{C,E},{D,E}

y Therefore, = +

n r 5 2

21

Smarter Version in Java

y n = 0: a^0 = 1

y n nonzero and even: an^ = (an/2^ ) 2

y n nonzero and odd: an^ = a·(an/2^ ) 2

static int power(int a, int n) { if (n == 0) return 1; int halfPower = power(a,n/2); if (n%2 == 0) return halfPowerhalfPower; return halfPowerhalfPowera; }*

parameters

local variable

yThe method has two parameters and a local variable yWhy aren’t these overwritten on recursive calls? (^22)

y Key idea:

ƒ Use a stack to remember parameters and local variables across recursive calls ƒ Each method invocation gets its own stack frame

y A stack frame contains storage for

ƒ Local variables of method ƒ Parameters of method ƒ Return info (return address and return value) ƒ Perhaps other bookkeeping info

How the compiler implements recursive methods

23

y Like a stack of plates y You can push data on top or pop data off the top in a LIFO (last-in- first-out) fashion y A queue is similar, except it is FIFO (first-in-first-out)

Stacks

top element

2nd element

3rd element

bottom

element

top-of-stack pointer

stack grows

24

Stack Frame

y A new stack frame is

pushed with each

recursive call

y The stack frame is

popped when the

method returns

ƒ Leaving a return value (if there is one) on top of the stack

a stack frame

return info

local variables

parameters

Example: power(2, 5)

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 2

(hP = )?

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 2

(hP = )?

return info

(a = ) 2

(n = ) 1

(hP = )?

return info

(a = ) 2

(n = ) 5

(hP = ) 4

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 2

(hP = ) 2

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 2

(hP = )?

return info

(a = ) 2

(n = ) 1

(hP = ) 1

(retval = ) 1

(retval = ) 2

(retval = ) 4

(retval = ) 32

How Do We Keep Track?

y At any point in execution, many invocations of power may be in existence ƒ Many stack frames (all for power ) may be in Stack ƒ Thus there may be several different versions of the variables a and n

y How does processor know which location is relevant at a given point in the computation? ƒ Frame Base Register Š When a method is invoked, a frame is created for that method invocation, and FBR is set to point to that frame Š When the invocation returns, FBR is restored to what it was before the invocation

y How does machine know what value to restore in the FBR? ƒ This is part of the return info in the stack frame

27

FBR

y Computational activity takes place only in the topmost (most recently pushed) stack frame

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 2

(hP = )?

return info

(a = ) 2

(n = ) 5

(hP = )?

return info

(a = ) 2

(n = ) 2

(hP = )?

return info

(a = ) 2

(n = ) 1

(hP = )?

FBR (^) FBR FBR

old FBR

old FBR

old FBR

old FBR old FBR old FBR

28

Iteration or recursion?

y Some languages do not support recursion, others do not

support iteration

ƒ But many modern languages support both

y How to choose?

ƒ Which is clearer? Which is more intuitive? (often recursion) ƒ Which is faster? Which uses less memory? (often iteration)

y Recursion involves some overhead

ƒ Memory overhead: stack frames ƒ Execution time overhead: method calls

Conclusion

y Recursion is a convenient and powerful way to define

functions

y Problems that seem insurmountable can often be

solved in a “divide-and-conquer” fashion:

ƒ Reduce a big problem to smaller problems of the same kind, solve the smaller problems ƒ Recombine the solutions to smaller problems to form solution for big problem