Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS180 RECURSION March 28,2008. Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be.

Similar presentations


Presentation on theme: "CS180 RECURSION March 28,2008. Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be."— Presentation transcript:

1 CS180 RECURSION March 28,2008

2 Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be handed out. Exam 2 grades are available on blackboard. Exam 2 key has been posted on the course website.

3 What is Recursion? Calling of a method from within the definition of the same method. -known as recursive call, or recursive invocation. e.g. factorial(n) = n*factorial(n-1); Recursion improves clarity of the program. Suitable to problems that can be solved by solving a smaller version of itself. Recursive calls may or may not return a value.

4 Recursion Guidelines The method definition can be a branching statement leading to different cases based on some parameter being supplied. One or more of them generally work on smaller sections of the task to be performed. This involves a recursive call to the same function. One or more of them should have no recursive calls and should ensure termination of the recursive flow. These branches are known as stopping cases or base cases.

5 Simple Example: Sum of first ‘n’ natural numbers Class MySum { public static void main(String args[])‏ { MySum s = new MySum(); int n = 6; System.out.println(“Sum of “+n+” numbers is “+s.nsum(n)); } public int nsum(int n)‏ { if (n == 1) return 1; // Stopping condition else return n + nsum(n-1); // Recursive call to smaller problem }

6 Working of Recursion.. nsum(6) 21 6 + nsum(5)6 + 15 5 + nsum(4)5 + 10 4 + nsum(3)4 + 6 3 + nsum(2)3 + 3 2 + nsum(1)2 + 1 Stopping condition at n = 1. Calls Evaluations

7 More examples 1) public static void inWords(int number){ if (number < 10) print(digitWord(number)+” “); else { inWords(number/10);  Stmt 1 print(digitWord(number%10) + “ “);  Stmt 2 } What if Stmt 1 and Stmt 2 are in the reverse order ? 2) Revisiting the quiz in class: (No for/while loops, just if-else needed)‏ Method returns true if a[i]==b[i] ….. a[n] == b[n] ; false otherwise public boolean same(int a[],int b[], int i, int n) { if (i==n)‏ return (a[i] == b[i]); else return (a[i] == b[i]) && same(a,b,i+1,n); }

8 More examples 1 2 3 A =2 1 2 det(A) = 1(1*1-1*2) - 2(2*1-3*2) + 3(2*1-3*1)‏ 3 1 1 = 4 Smaller matrix is obtained by removing i th row and the j th column where the circled number is A i,j Circled numbers should belong to a single row / column. Can be extended to any NxN matrix. Pseudo code: (iteration + recursion)‏ if (size is 2x2 ) return (ad-bc); else (-1) 1+1 A 1,1 *det(mA 1,1 ) + (-1) 1+2 A 1,2 *det(mA 1,2 ) + ….. (-1) 1+n A 1,n *det(mA 1,n ) det(smaller matrix) ‏

9 Recursion vs Iteration Cons: Recursion in general is less efficient than iteration. More complicated as we need to keep track of the recursive calls and suspended computations to debug the flow. Pros: Better expresses the intent of the program. In most cases, shorter and easier to write when compared to the corresponding iterative definition.

10 Infinite recursion If the recursive call does not solve a smaller/simpler version of the problem, a base case may never be reached. This leads to the method calling itself repeatedly. (Eventually results in a stack overflow.)‏ This is known as Infinite Recursion. int factorial(int n)‏ { // Base condition missing. When would this stop ? return n* factorial(n-1); }

11 Binary Search Linear search in a sorted array : for (int i=0;i< arr.length;i++)‏ if (arr[i] == num) return num; What if the number we are looking for is the last number on the array? Use binary search for sorted arrays. Quicker !

12 Binary Search contd.. Search using recursion: mid = (first + last)/2 if (first > last)‏ return -1; else if (target == a[mid])‏ return mid; else if (target < a[mid] search a[first] through a[mid-1] else search a[mid + 1] through a[last] Size of array to be searched reduced to about half the size in each call. Note: No suspended computation to track as in previous examples (factorial, sum of n numbers etc.,)‏

13 Merge Sort Algorithm: If the array has only one element, do nothing. Copy the first half of the elements into an array named front. Copy the second half of the elements into an array named tail. Sort array front recursively. Sort array tail recursively. Merge arrays front and tail.

14 4 6 2 8 9 3 1 8 9 3 1 4 6 2 4 6 2 6 2 2 6 2 4 6 8 9 3 1 8 9 3 1 8 9 1 3 1 3 8 9 1 2 3 4 6 8 9

15 Merge sort

16

17 Exam 2 Questions 2) System.out.println - example for Overloading Recall println takes in arguments of various data types. 3) import and package : import univ.* does not import classes in sub-directories like univ.people etc., import univ.*.* invalid. package univ.* invalid.

18 Exam 2 Questions 9) Class not commonly used in reading text file – ObjectInputStream. Recall its usage in reading binary files. 11) public class Sta { private static double d = 0; // shared copy private double e = 0; // instance variable public Sta () { ++d ; ++e; } public static void main(String [] args) { Sta s1 = new Sta();  d is 1, e is 1 Sta s2 = new Sta();  d is 2, e is 1 double r = d + s1.e + s2.e; } r = 4.0

19 Exam 2 Questions 13) Points to remember: * Cannot instantiate interfaces, abstract classes * An instance of a class can be assigned to a reference variable of a class/interface above this class in the hierarchy. 14) B extends A A aObj = … B bObj = (B) aObj; * B comes below A in the hierarchy. Hence reference variable of type B holding an instance of A may not be safe. * Resolved at runtime. Why not compile time? (What if A aObj = new B() )‏

20 Exam 2 Questions 16)‏ public class A{ private int i = 1; public int getI (){ return I; } } public class B extends A { private int i; public B (int i)‏ { this.i = I; } public int sum (A a) { return (i + getI() + a.getI()); } public static void main (String[] args){ B b = new B(2); int result = b.sum(b); } Result is 4 Note that there is no getI() in B ; inherited from A. Suppose i is public, are a.i and i in the method sum same??

21 Exam 2 Questions 20) public class A{ public static void f(int[] arr){ for (int k=0; k<arr.length; k++)‏ arr[k] = arr[k] * arr[k]; } public static void g(int[] arr, int x){ int[] temp = arr; arr = new int[temp.length * x]; for (int k=0; k<arr.length; k++)‏ arr[k] = temp[k % temp.length]; } public static void main(String[] args){ int[] arr = {1, 2, 3, 4, 5}; f(arr); ----  arr = { 1,4,9,16,25} g(arr, 2); ---  arr = { 1,4,9,16,25} -- ? for (int k=0; k<arr.length; k++)‏ System.out.print(arr[k] + " "); } arr here is not same as the arr passed from main. It is a reference to the same location as the ‘arr’ in main. This statement changes its reference to a different location. Hence, we can stop worrying about any modifications from this point.

22 Project 7 Polish notation : / * + 8 #1 -7 #5 #1: + 1 2 #5: * 3 -4 Parsed into a HashMap: Key Value 1 + 1 2 5 * 3 -4 Value of above expression : (Use recursion)‏ / * + 8 (3) -7 (-12) = / * (11) -7 (-12) = / -77 -12 = 6 /,*,+,-... --- Token Type : OP (operator)‏ 1,3,-5 … --- Token Type : INT (integer)‏ #4, #57 …. --- Token Type : LABEL ( value to be returned is the corresponding expression)‏

23 Quiz Write a program to find the number of prime numbers between two positive integers n 1 and n 2 (inclusive) using recursion. Assume you already have a boolean function isPrime(n) provided.


Download ppt "CS180 RECURSION March 28,2008. Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be."

Similar presentations


Ads by Google