Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion … just in case you didn’t love loops enough …

Similar presentations


Presentation on theme: "Recursion … just in case you didn’t love loops enough …"— Presentation transcript:

1 Recursion … just in case you didn’t love loops enough …

2 Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is awkward or “inelegant” Each recursive call is given a smaller portion of the original problem Last recursive call solves diminished problem without recursion

3 Example // method writes digits of a non-negative number, stacked vertically public void write_vertical(int n) { n = Math.abs(n); if (n < 10) System.out.println(“” + n); else { write_vertical(n / 10); System.out.println(“” + n % 10); }

4 Tracing recursive method write_vertical 1. write_vertical(52406); n=52406 n/10=5240 2. write_vertical(n/10) ; n=5240 n/10=524 3. write_vertical(n/10); n=524 n/10=52 4. write_vertical(n/10); n=52 n/10=5 5. write_vertical(n/10); n=5 Stop recursion! Output: 6. System.out.println(“” + n); 5 2 4 0 6 7. System.out.println (“” + n%10); 8. System.out.println (“” + n%10); 9. System.out.println(n%10); 10. System.out.println (“” + n%10);

5 Elements of recursive method Base caseBase case: problem is simplified to the point where recursion becomes unnecessary: n < 10 Variant expressionVariant expression: the part of the problem that changes, making the problem smaller: n Recursive callRecursive call: method calls itself: write_vertical (n / 10);

6 How recursion works Activation record: memory block that stores all the information a method needs to work: –values of local variables & parameters –where method should return to (so calling method can resume execution)

7 How recursion works When a method call is encountered, execution of current method ceases Information for newly called method is stored in an activation record Method executes

8 How recursion works If new method contains another method call, the process just described repeats Each recursive call generates its own activation record –as each recursive call is encountered, previous activation record is stored on run-time stack –when last call fails to generate a new activation record, stacked calls are removed (in reverse of the order they were stored), and each process continues in succession

9 Remember, for a recursive method to be successful... Must be a problem with one or more cases in which some subtasks are simpler versions of the original problem - use recursion for these Must also have one or more cases in which entire computation is accomplished without recursion (base case)

10 Another example: the powers method Suppose you wanted to find the value of X n For most values of n, we can solve this iteratively using a simple loop: int answer = 1; for (int c = 1; c <= n; c++) answer *= X; We can take care of the cases of n=1 or n=0 with simple if statements; but what about a negative value of n?

11 Finding a recursive solution We can observe that for any value of n, X n is equal to X * X (n-1) Armed with this information, we can easily develop a recursive solution that covers all values of X and n

12 Recursive power method double rpower (double X, int n) { if (X == 0) return 0; else if (n == 0) return 1; else if (n > 0) return X * rpower(X, n-1); else // n < 0 return 1 / rpower(X, -n); }

13 Drawing pictures with recursion We used ASCII art to illustrate how iteration worked – we can do the same with recursion For example, if we wanted to draw a line using several instances of a single character, we could write a loop like the one below: for (int x = lineLen; x > 0; x--) System.out.print(“$ ”); We can do the same task recursively; see next slide

14 Example public void drawLine (int x) { if (x == 0) return; System.out.print(“$”); drawLine(x-1); }

15 Same example, slightly different The original iterative line drawing routine was different from typical examples we’ve seen in the past, in that the counter was counting down instead of up I did this to illustrate how the iterative version relates to the recursive version – the problem (value of counter) gets smaller with each loop iteration, or each recursive call The situation is the same if we have the counter counting up, but it’s a little harder to see

16 Example Iterative version: for (int x = 0; x < someConstant; x++) System.out.print (“$ ”); Equivalent recursive version: public drawLine (int x, int someConstant) { if (x < someConstant) { System.out.print(“$”); drawLine (x+1, someConstant); } distance between Instead of x getting smaller, the distance between x and someConstant gets smaller

17 Drawing prettier pictures: random Fractals Fractals are mathematical phenomena that describe the kinds of seemingly random shapes that occur in nature Graphics programmers use fractals to draw natural-looking scenes Your textbook (as paraphrased on the next slide) describes one method for generating random fractals

18 Fractals made simple 1. Start with a line; find its midpoint: 2. Bend the line at the midpoint, using a random angle: 3. Lather, rinse, repeat:

19 An applet for fractals When we draw the lines that make up a fractal, we continually perform 3 tasks: –find the midpoint of a line –randomly generate a distance –draw two new lines, which stretch from a point the generated distance above the midpoint to the points at the two ends of the original line

20 An applet for fractals We keep performing the three tasks described, breaking the original line into smaller and smaller segments until some end state is reached If we think of the end state as being the minimum distance we want to allow between any two points (or the minimum length of a line segment), we can come up with a recursive solution that starts with the original line length and stops when we have reached the minimum for each segment

21 The heart of the matter: the randomFractal method public void randomFractal( int leftX, int leftY, int rightX, int rightY, Graphics drawingArea) { final int STOP = 4; // When length < EPSILON, draw a line segment int midX, midY; // Midpoints in the x and y dimensions int delta; // Amount to shift the line's midpoint up or down if ((rightX - leftX) <= STOP) drawingArea.drawLine(leftX, leftY, rightX, rightY); else { midX = (leftX + rightX) / 2; midY = (leftY + rightY) / 2; delta = rg.nextInt(rightX - leftX); midY += delta; randomFractal(leftX, leftY, midX, midY, drawingArea); randomFractal(midX, midY, rightX, rightY, drawingArea); } }

22 Searching an array We have discussed the problem of searching for a value within an array With unsorted data, our only real option is to start at one end of the array and search until we either find the target value or exhaust all of the possibilities The method on the next slide illustrates such a process

23 Serial search – the brute force way public int serialSearch(int n) { for (int x = 0; x < size; x++) if (array[x] == n) return x; return -1; } Worst case, this method is O(n)

24 A recursive search method A more efficient search method can be defined recursively, and is somewhat analogous to the random fractal example: –check value at midpoint; if not target then –if greater than target, make recursive call to search “upper” half of structure –if less than target, recursively search “lower” half Works only if data are sorted

25 Binary search code public int binarySearch(int n, int first, int extent) { int mid = extent/2; if (extent == 0) return -1; else { if (array[mid] n) binarySearch(n, mid+1, (extent-1)/2); return mid; } }

26 searching26 Binary search in action Suppose you have a 13-member array of sorted numbers: 5 14 23 47597182 99108113130 151 172 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] Searching for value: 113 Initial function call:first = 0, extent = 13, mid = 6

27 searching27 Binary search in action 5 14 23 47597182 99108113130 151 172 Searching for value: 113 Initial function call:first = 0, extent = 13, mid = 6 Since 113 != 82, make recursive call: binarySearch (target, mid+1, (extent-1)/2); [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

28 searching28 Binary search in action 5 14 23 47597182 99108113130 151 172 Searching for value: 113 Recursive call(1):first = 7, extent = 6, mid = 10 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

29 searching29 Binary search in action 5 14 23 47597182 99108113130 151 172 Searching for value: 113 Recursive call(1):first = 7, extent = 6, mid = 10 Since 113 != 130, make recursive call: binarySearch(target, first, extent/2); [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

30 searching30 Binary search in action 5 14 23 47597182 99108113130 151 172 Searching for value: 113 Recursive call(2):first = 7, extent = 3, mid = 8 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

31 searching31 Binary search in action 5 14 23 47597182 99108113130 151 172 Searching for value: 113 Recursive call(2):first = 7, extent = 3, mid = 8 Since 113 != 108, make recursive call: binarySearch(target, mid+1, (extent-1)/2); [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

32 searching32 Binary search in action 5 14 23 47597182 99108113130 151 172 Searching for value: 113 Recursive call(3):first = 9, extent = 1, mid = 9 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

33 searching33 Binary search in action 5 14 23 47597182 99108113130 151 172 Searching for value: 113 Recursive call(3):first = 9, extent = 1, mid = 9 Since 113 == 113, target is found; found = true, location = 9 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

34 searching34 Binary Search Analysis Worst-case scenario: item is not in the array –algorithm keeps searching smaller subarrays –eventually, array size will be 0, and the search will stop Analysis requires computing time needed for operations in function as well as amount of time for recursive calls We will analyze the algorithm’s performance in the worst case

35 searching35 Step 1: count operations Test base case: if (extent==0) 1 operation Compute midpoint: mid = first + extent/2; 3 operations Test for target at midpoint: if (target == array[mid])2 operations Test for which recursive call to make: if (target < array[mid])2 operations Recursive call - requires some arithmetic and argument passing - estimate 10 operations

36 searching36 Step 2: analyze cost of recursion Each recursive call is preceded by 18 (or fewer) operations Multiply this number by the depth of recursive calls and add the number of operations performed in the stopping case to determine worst-case running time (T(n)) T(n) = 18 * depth of recursion + 3

37 searching37 Step 3: estimate depth of recursion Calculate upper bound approximation for depth of recursion; may slightly overestimate, but will not underestimate actual value –Each recursive call is made on an array segment that contains, at most, N/2 elements –Subsequent calls are always made on size/2 –Thus, depth of recursion is, at most, the number of times N can be divided by 2 with a result > 1

38 searching38 Estimating depth of recursion Referring to “the number of times N is divisible by 2 with result > 1” as H(n), or the halving function, the time expression becomes: T(n) = 18 * H(n) + 3 H(n) turns out to be almost exactly equal to log 2 n: H(n) = log 2 n meaning that fractional results are rounded down to the nearest whole number (e.g. 3.7 = 3) -- this notation is called the floor function

39 searching39 Worst-case time for binary search Substituting the floor function of the logarithm for H(n), the time expression becomes: T(n) = 18 * ( log 2 n ) + 3 Throwing out the constants, the worst- case running time (big O) function is: O(log n)

40 searching40 Significance of logarithms Logarithmic algorithms are very fast because log n is much smaller than n The larger the data set, the more dramatic the difference becomes: –log 2 8 = 3 –log 2 64 = 6 –log 2 1000 < 10 –log 2 1,000,000 < 20

41 searching41 For binary search algorithm... To search a 1000 element array will require no more than 183 operations in the worst case To search a 1,000,000 element array will require less than 400 operations in the worst case

42 When Not to Use Recursion When recursive algorithms are designed carelessly, it can lead to very inefficient and unacceptable solutions In general, use recursion if –A recursive solution is natural and easy to understand. –A recursive solution does not result in excessive duplicate computation. –The equivalent iterative solution is too complex.

43 Preventing infinite recursion One-level recursion: every case is either a stopping case or makes a recursive call to a stopping case Since most recursive functions are, or have the potential to be, recursive beyond just one level, need more general method for determining whether or not recursion will stop

44 Preventing infinite recursion variant expressionDefine a variant expression –numeric quantity that decreases by a fixed amount on each recursive call threshold valueBase case is when variant expression is less than or equal to its threshold value


Download ppt "Recursion … just in case you didn’t love loops enough …"

Similar presentations


Ads by Google