Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review of Recursion. Definition: Recursion - The process of a function calling itself.

Similar presentations


Presentation on theme: "Review of Recursion. Definition: Recursion - The process of a function calling itself."— Presentation transcript:

1 Review of Recursion

2 Definition: Recursion - The process of a function calling itself.

3 Key considerations: A clearly defined stopping state must exist. Any recursive subprogram can be rewritten using iteration and a stack.

4 Example Write a function to sum the elements of an integer array. There are several ways this task could be accomplished.

5 The Iterative Approach int sum(List A) { int i, total; total = 0; for (i = 0; i < SIZE; i++) total += A[i]; return total }

6 Two recursive approaches Here is a truly recursive approach to the summation problem described above. The rationale is simple, the sum of A may be viewed as A[0]+A[1]+A[2]+A[3]+A[4] or...

7 it may also be seen as A[0]+ Sum(A,1) (where Sum(A,1) is the sum of the elements in the list beginning with the second one). Similarly, Sum(A,1) is A[1] + Sum(A,2); Sum(A,2) is A[2] + Sum(A,3); Sum(A,3) is A[3] + Sum(A,4); and finally... Sum(A,4) is simply A[4] since n is 5 we are now at the end of the list.

8 General definition In general, for all lists A with SIZE elements, we define the process as follows: 0 <= i < SIZE-1: Sum(A,i) = A[i] + Sum(A,i+1) and i = SIZE-1: Sum(A,i) = A[i] { base case}

9 Example: This can be written recursively as int sum(List A, int i) { if (i == SIZE-1) then return A[i] else return A[i] + sum(A,i+1) }

10 Code and definitions Notice how closely the code for this procedure conforms to our formal definition. This is one of the advantages of recursive programming as some problems can best be stated only in recursive terms. Note also that the values are added in reverse order by this procedure. If A[0]=3, A[1]=7,A[2]=8,A[3]=1, A[4]=4...

11 The iterative solution int sum(List A) { int i, total; total = 0; for (i = SIZE; i >= 0; i--) total += A[i]; return total }

12 Demonstration problems Here are a few short problems that demonstrate recursive thinking. To print the elements in a list: Definition: 0 <= i < SIZE-1: print A[i] then print_list(A,i+1) –{ print one element then the rest} i = SIZE-1: print A[i] –{ terminal condition print the last element}

13 Iterative solution void print_list(List A) { int i; for (i = ; i< SIZE; i++) cout << A[i]; }

14 Recursive solution void print_list(List A, int i); { If (i == SIZE-1) cout << A[i] else { cout << A[i]; print_list(A,i+1) } };

15 How could we make it print backwards?

16 Iterative solution void print_list(List A) { int i; for (i = SIZE; i >= 0; i--) cout << A[i]; }

17 Recursive solution void print_list(List A, int i) { If (i == Size-1 ) cout << A[i] else { print_list(A,i+1) cout << A[i]; } }

18 Now, rewrite the program segment discussed earlier so that it recursively sums up the list from the first element to the last? In other words, like this only without iteration:

19 Summation (iterative) int sum(List A) { int i, total; total = 0; for (i = 1; I < SIZE; I++) total += A[i]; return total; }

20 Recursive Planning Keep in mind that you should first come up with a formal definition of the recursive process. Such definitions have two parts, –one specifies the stopping condition (base case) –and the other keeps things going.

21 Summation int sum(List A, int i) { if (i == 0) return A[i] else return sum(A,i-1) + A[i] };

22 Sample recursion problems Write a recursive routine to find the sum of a list of integers. Write a recursive routine to compare two lists to see if they are the same. Write a recursive routine to determine whether a target value is in a list of integers (ie. return a boolean value T or F). Write recursive routines to print strings of characters forward and backward.

23 The Costs of Recursion There are two main costs –Space: maximum size of the stack –Time: number of recursive calls made Examples

24 Factorial Program int fact(int n) { If (n == 0) return 1 else return n * fact(n-1) } Space cost: O(N) (stack) Time cost: O(N) (recursive calls)

25 A Classic Problem in Recursion “The Towers of Hanoi” A puzzle in which disks are moved from one tower to another according to the following set of rules...

26 Tower of Hanoi Rules When a disk is moved from one peg it must be placed on another. Only one disk may be moved at a time, and it must be the top disk on a tower. A larger disk may never be placed upon a smaller disk.

27 The Towers of Hanoi Legend Legend has it that the priests in the Temple of Bramah were given a puzzle consisting of a golden platform with three diamond needles, on which were placed 64 golden disks. The priests were to move one disk per day, following the preceding rules. When they had successfully completed their task, time would end.

28 A single disk tower ABC

29 ABC

30 A two disk tower ABC

31 Move 1 ABC

32 Move 2 ABC

33 Move 3 ABC

34 A three disk tower ABC

35 Move 1 ABC

36 Move 2 ABC

37 Move 3 ABC

38 Move 4 ABC

39 Move 5 ABC

40 Move 6 ABC

41 Move 7 ABC

42 Simplifying the method for 3 disks Step 1. Move the top 2 disks from A to B using C as intermediate Step 2. Move the remaining disk from A to C Step 3. Move 2 disks from B to C using A as intermediate

43 Thus, the problem for 3 disks becomes: A recursive step. –Moving 2 disks. A recursive out. –A one disk move. –The base case

44 Towers of Hanoi void Hanoi(int n, char S,D,I); { if (n==1) cout << “Move from “,S,“ to “, D) else {Hanoi(n-1,S,I,D); cout << “Move from “,S,”to “,D; Hanoi(n-1,I,D,S) } }

45 Summary of total moves.

46 If you call Hanoi with...it takes... 1 disk Hanoi(1,'A','C','B') 1 move 2 disks Hanoi(2,'A','C','B') 3 moves 3 disks Hanoi(3,'A','C','B') 7 moves 4 disks Hanoi(4,'A','C','B') 15 moves 5 disks Hanoi(5,'A','C','B') 31 moves. 20 disks...1,048,575 moves 21 disks...2,097,151 moves

47 Space cost: O(n) Time cost: O(2 n ) Suppose your machine executed 400 million instructions/second then... DisksExecution time (seconds) 20.0025 second 302.5 seconds 4042 minutes 5029.2 days 6080 years 7080,000 years 8083 million years

48 The end of time So, at 1 disk per day it would take approximately 400,000,000*365.4*24*60*60 = 12,600,000,000,000,000 years or about a million times the current estimated age of the universe

49 Analysis n This is O( 2 ) –about as bad as we have ever seen Big-O get Nevertheless, it gets the job done with a minimal amount of code.

50 Conclusions about recursion. Advantages –Concise, elegant algorithms –No explicit loop controls Disadvantages –Stack operations are costly. –Stack is finite


Download ppt "Review of Recursion. Definition: Recursion - The process of a function calling itself."

Similar presentations


Ads by Google