cs102 – recursion david davenport bilkent university ankara – turkey email: [email protected]...

30
CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: [email protected] Spring 2003

Post on 21-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

CS102 – Recursion

David DavenportBilkent UniversityAnkara – Turkey

email: [email protected] 2003

Page 2: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

What is Recursion? Method of solving problems Alternative to iteration All recursive solutions

can be implemented iteratively Characteristic...

recursive methods call themselvesrecursive functions defined in terms of (simpler versions) themselves

General recursive case & stopping cases

Page 3: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Factorial N Iterative

N! = N * N-1 * N-2 … 2 * 1

Recursive 1! = 1 - stopping case N! = N * (N-1)! - general case

implement & trace in Java

Page 4: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

So, why use recursion? Advantages...

Interesting conceptual framework Intuitive solutions to difficult problems

But, disadvantages... requires more memory & time requires different way of thinking!

Page 5: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Towers of Hanoi The Problem…

Rules only move one disk at a time can’t put a disk on a smaller one

Monks believed world would end once solved for 64 disks!

Takes 580 billion years!

at one move per sec.

Page 6: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Hanoi… http://www.mazeworks.com/hanoi/

private void moveTower (int numDisks, int start, int end, int temp) { if (numDisks == 1) moveOneDisk (start, end); else { moveTower (numDisks-1, start, temp, end); moveOneDisk (start, end); moveTower (numDisks-1, temp, end, start); } }

Page 7: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Print reverse Print first N values in reverse

Simple iterative solution… Recursive?

Hint - what is the simplest case? Write out sequence of cases

& look for previous case within each casegeneralise & note stopping case!

5 7 2 6 3Given... print...

3, 6, 2, 7, 5

Page 8: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Print reverse - solution Solution form

5 7 2 6 3

N’thN-1

To print N values in reverse order if N > 0

Print the N’th value& thenPrint the preceding N-1 values in reverse order

Write Java & trace

Page 9: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Print forward Print set of values in normal order Solution form

5 7 2 6 3

N’thN-1

To print N values in normal order if N > 0

Print the first N-1 values in normal order& thenPrint the N’th value

Write Java & trace

Page 10: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Print – alternative solution Print set of values in order Alternative solution

5 7 2 6 3

To print values btw S & E in order if S <= E

Print the value at S& thenPrint the values btw S+1 & E in order

Write Java & tracefirst S rest E

Page 11: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Find Max Find max of first N values

5 7 2 6 3

To find max of N values if N = 1

return N’th value else

return greater of N’th & max of preceding N-1 values

N’thN-1

Think about solution in terms of

these two sub-

problems

Page 12: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Sequential search

5 7 2 6 3

Search( first N values of X for target) if N = 0

return not found else if N’th value is target

return found at N’th else

return search( first N-1 values of X for target)

N’thN-1

Think about simplest cases of problem & more

general solution in terms of these two

sub-problems

O(N)O(N)

Page 13: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Binary Search

• Think about using telephone directory• Values must be in order!• Have knowledge of data distribution• If unknown? (number guessing game)

1 2 3 5 6 7 9second halffirst half

middleS E

O(log2N)O(log2N)

Page 14: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Binary Search (continued…)

Search( X btw S & E for target) if S > E

return not found else if ( middle value is target)

return found at middle else if ( target < middle value)

return search( first half of X for target) else

return search( second half of X for target)

First half is S, middle-1

Second half is middle+1, E

Page 15: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Selection sort

5 7 2 6 3

N’thN-1

selectionSort( first N values of X) if N > 1

locOfMax = findmax( first N values of X)exchange N’th value with value at locOfMaxselectionSort( first N-1 values of X)

O(N2)O(N2)

locOfMax

Page 16: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

QuickSort

5 7 3 9 2 1 6

pivot

O(Nlog2N)O(Nlog2N)

QuickSort( X btw S & E) if S < E

pivot loc. = partition( X btw S & E)QuickSort( first part of X)

QuickSort( second part of X)

Sort second partSort first part

2 1 3 5 7 9 6

pivot

First part isS to pivot loc.-1Second part ispivot loc.+1 to E

partition

Page 17: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

MergeSort

O(Nlog2N)O(Nlog2N)

MergeSort( X btw S & E) if S < E

MergeSort( first half of X) MergeSort( second half of X)

Merge( first & second halves of X)

1 5 7 9 2 3 6

1 2 3 5 6 7 9merge

Merge isthe basis of sequential processing

Sort first halfSort second half

Page 18: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Counting Count number of values before zero

5 7 2 0 3

count no. values before zero starting at S if value at S is zero

return 0 else

return 1 + count no. values starting at S+1

restfirst S

Zero is sentinel value& so is guaranteed to exist.This is a common form of representation for strings!

Page 19: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Common mistakes! (1)

sum = 0;

public void count( int[] X, int S) { if ( X[S] != 0) {

sum++;count( X, S+1);

}}

Problems:• Need another method to getCount()• What happens if called again?

Page 20: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Common mistakes! (2)

public int count( int[] X, int S) { int sum; if ( X[S] == 0)

return sum; else {

sum++;return count( X, S+1);

}}

Problem:• New instance of local variable for each instantiation!

Page 21: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Palindrome

R A D A R

lastfirstmiddle

isPalindrome( word) if first >= last

return true else if first char of word != last char of word

return false else

return isPalindrome( middle of word)

Page 22: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Fibonacci Numbers Find fib(n) given the definition :

fib(0) = 1 f ib(1) = 1 fib(n) = fib(n-1) + fib(n-2)

Page 23: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Solutionpublic int fib( int n ) {

if ( n == 0 || n == 1 ) { return 1;

} else { return fib( n - 1 ) + fib( n - 2 );

} }

naturally recursive, however better-off beingsolved iteratively

Page 24: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Caching solutions ..static int fib(int n) {

int[] sols = new int[n + 1];sols[0] = 1; sols[1] = 1;return fib(n, sols)

}static int fib(int n, int[] sols) {

if (sols[n] > 0) return sols[n];int sol = fib(n-1, sols) + fib(n-2, sols);sols[n] = sol;return sol;

}

Page 25: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Blob Count

A Blob is the union of adjacent cells

Cells are represented by a two dimensional array: boolean[][] isFull;

The problem is to count the size of a blob starting from coordinates x, & y.

Page 26: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Blob Count, the plan have a recursive method that adds 1

to the count if the given cell is occupied, and recursively adds the numbers of 8 neighbors

we need to remember which cells we already counted, and can use boolean[][] counted for this purpose

Page 27: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Blob count, algorithmpublic int count(boolean[][] cells, int x, int y){

boolean[][] counted = new boolean[cells.length][cells[0].length]

return count_(cells, counted, x, y)}

Page 28: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

Blob Algorithmprivate int count_(boolean[][] cells, boolean[][] counted,

int x, int y) {if ( x < 0 || x >= cells.length)

return 0;if (y < 0 || y >= cells[0].length)

return 0;if ( counted[x][y]) return 0;if (!isFull[x][y]) return 0;counted[x][y] = true;return 1 + count_(cells, counted, x+1, y)

+ count_(cells, counted, x, y+1) + count_(cells, counted, x+1, y+1) + …

}

Page 29: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003

The plan… Print set of N values forward & backward Repeat using S & E find max value search for target - sequential binary search sort - selection, quick, merge palindrome Count using S only Maze & blob counting Fractals? Recursive-descent-parsing? …on to data structures

(stacks, queues, lists, trees, …)

Page 30: CS102 – Recursion David Davenport Bilkent University Ankara – Turkey email: david@bilkent.edu.tr Spring 2003