1 / 22

Data Structures( 数据结构 ) Course 6:Recursion

Data Structures( 数据结构 ) Course 6:Recursion. Recursion( 递归 ): a repetitive process in which an algorithm call itself, that is recursive algorithm. Stack frame( 栈帧) : 在栈中为参数、返回地址和局部变 量保留的一块内存区 , 必要时在过程 调用中使用。 Factorial( 阶乘 ): the product of the integral values from 1 to the number.

clara
Télécharger la présentation

Data Structures( 数据结构 ) Course 6:Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Structures(数据结构)Course 6:Recursion

  2. Recursion(递归): a repetitive process in which an algorithm call itself, that is recursive algorithm. Stack frame(栈帧): 在栈中为参数、返回地址和局部变量保留的一块内存区,必要时在过程调用中使用。 Factorial(阶乘): the product of the integral values from 1 to the number. Fibonacci number(斐波纳契数列) The towers of hanoi(汉诺塔) Vocabulary

  3. Highlights in this chapter • Factorial – A classical recursive case • How recursion works • Fibonacci number – Another recursion case • The towers of hanoi -- A classic recursive algorithms

  4. 6-1 Factorial – A case study Factorial(3) = 3*2*1=6 • Factorial definition: the factorial of a number is product of the integral values from 1 to the number. Iteration algorithm definition Recursion algorithm definition 1 if n = 0 Factorial(n) = n*(n-1)*(n-2)*…*3*2*1 if n > 0 Factorial(3) = 3* Factorial(2) Factorial(3)=3*2 =6 Factorial(2) = 2* Factorial(1) Factorial(2)=2*1 =2 Factorial(1) = 1* Factorial(0) Factorial(1)=1*1 =1 Factorial(0) = 1 1 if n = 0 Factorial(n) = n*( Factorial(n-1)) if n > 0

  5. Recursive factorialAlgorithm Iterative factorialalgorithm Algorithm recursiveFactorial (val n <integer>) Calculates the factorial of a number using recursion Pre n is the number to be raised factorially Return n! is returned 1 if (n equal 0) 1 return 1 2 else 1 return (n * recursiveFactorial(n - 1)) 3 end if end recursiveFactorial Algorithm iterativeFactorial (val n <integer>) Calculates the factorial of a number using a loop. Pre n is the number to be raised factorially Return n! is returned 1 i = 1 2 factN = 1 3 loop (i <= n) 1 factN = factN * i 2 i = i + 1 4 end loop 5 return factN end iterativeFactorial

  6. When the power is called, the stackframe is created. It contains four elements: 1. The parameters to be processed by the called algorithm 2. The local variables in the calling algorithm 3. The return statement in the calling algorithm 4. The expression that is to receive the return value 6-2 How recursion works • How any call works • ProgramtestPower • Read (base, exp) • Result = power(base, exp) • Print (base * exp = result) • End testPower • Algorithm power (base <integer>, • exp < integer >) • Num = 1 • Loop (exp >0) • 1 num = num * base • 2 exp = exp – 1 • End loop • Return num • End testPower

  7. 1. Parameters 5, 2 2. Local Var none 3. Return to testPower 4. Return value 5 * 5 1. Parameters 5, 2 2. Local Var none 3. Return to testPower 4. Return value unknown Stackframes for power(5,2) 1. Parameters 5, 1 2. Local Var none 3. Return to power 2.1 4. Return value 5 * 1 1. Parameters 5, 1 2. Local Var none 3. Return to power 2.1 4. Return value unknown 1. Parameters 5, 2 2. Local Var none 3. Return to testPower 4. Return value unknown 1. Parameters 5, 2 2. Local Var none 3. Return to testPower 4. Return value unknown Calls Return 1. Parameters 5, 0 2. Local Var none 3. Return to power 2.1 4. Return value 1 1. Parameters 5, 0 2. Local Var none 3. Return to power 2.1 4. Return value unknown 1. Parameters 5, 1 2. Local Var none 3. Return to power 2.1 4. Return value unknown 1. Parameters 5, 1 2. Local Var none 3. Return to power 2.1 4. Return value unknown 1. Parameters 5, 2 2. Local Var none 3. Return to testPower 4. Return value unknown 1. Parameters 5, 2 2. Local Var none 3. Return to testPower 4. Return value unknown How recursion works • Algorithm power ( val base <integer>, • val exp < integer >) • This algorithm computes the value of a number,base, raised to the power of an exponent ,exp. • Pre base is the number to be raised • Post value of base raised to power exp computed • return value of base raised to power exp returned • If (exp equal 0) • 1 return (1) • Else • 1 return (base * power (base, exp – 1 )) • End if • End power

  8. Recursive factorialAlgorithm

  9. 6-3 Designing recursive algorithm • The design methodology • Every recursive algorithm have two elements: • base case – solve a part of the problem • general case -- reduce the size of the problem Factorial(0) n * Factorial(n-1) • The rules for designing a recursive algorithm • 1. First ,determine the base case. • 2. Then determine the general case. • 3. Combine the base case and general case into an algorithm • Limitation of recursion • 1. Is the algorithm or data structure naturally suited to recursion? • 2. Is the recursive solution shorter and more understandable? • 3. Does the recursive solution run in acceptable time and space limits?

  10. pList 6 10 14 20 Design implementation reverse a linked list We need to print the list in reverse but not have reverse pointers: We print the list after find the last node(20). that is,we print node data as we back out of recursion • Algorithm printReverse ( val plist <pointer to node>) • Print singly linked list in reverse. • Pre list has been built • Post list printed in reverse • If (null plist) • 1 return • End if • Have reach end of list : print nodes • printReverse (plist->next) • Print (plist->data) • return • End printReverse base case: have found the last node(20). general case : if not reach the last node , to find the next node Algorithm : print linked list reverse

  11. Algorithm Analysis • We answer the three question of “Limitation of recursion” • 1. Is the algorithm or data structure naturally suited to recursion? • Linear list is not a naturally recursive structure, and the algorithm is not naturally suited to recursion. • 2. Is the recursive solution shorter and more understandable? • Yes. • 3. Does the recursive solution run in acceptable time and space limits? • The number of linear list node can become quit large ,also the algorithm has a linear efficiency (O(n)). ---- it is not a good for recursion. • thus : It is not a good candidate for recursion

  12. 6-4 Fibonacci number – another case study • Fibonacci number: Fibonacci number are a series in which each number is sum of the previous two numbers. The first few number in Fibonacci number are : • Program Fibonacci • This program prints out a Fibonacci series. • Print (This program prints a fibonacci series.) • Print (How many number do you want? ) • Read (seriesSize) • If (seriesSize < 2) • 1 seriesSize = 2 • end if • Print (First seriesSize Fibonacci number are: ) • Looper = 0 • Loop (looper < seriesSize ) • 1 nextFib = fib(looper) • 2 print (nextFib ) • 3 looper = looper + 1 • end loop • End Fibonacci 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …… • Algorithm: print Fibonacci number

  13. Fib(4) Fib(3) + Fib(2) Fib(2) + Fib(1) Fib(1) + Fib(0) 1 1 0 Fib(1) + Fib(0) 1 0 • Design algorithm of Fib(n): base case: Fib(0) = 0 , n = 0 Fib(1) = 1 , n = 1 general case : Fib (n) = Fib (n - 1) + Fib (n - 2) • Algorithm fib ( val num <integer>) • calculates the nth Fibonacci number. • Pre num identified the ordinal of the Fibonacci number • Post return the nth Fibonacci number. • If (num is 0 OR num is 1) • base case • 1 return num • End if • general case • Return (fib (num - 1) + fib (num - 2)) • End fib • The generalization of Fib(4) • The algorithm of Fib(n) • Algorithm Analysis calulate Fibonacci numbers is not efficient for more than 20 numbers.

  14. 6-5 The towers of hanoi • The towers of hanoi: monks had a set of three diamond needle, stacked on the first needle were 64 gold disk of decreasing size. The monks move one disk to another needle each hour, subject to the following rules: 1. Only one disk could be moved at a time. 2. A large disk must never be stacked above a smaller one. 3. One and only one auxiliary needle could be used for intermediate storage of disk. The legend said that when all 64 disk had been transferred to the destination needle,the world would end. • The towers of hanoi with only three disk (start position) Source auxiliary destination

  15. Steps of generalize the problem: case 1 : if we have only one disk to move case 2 : if we have two disk to move case 3 : if we have three disk to move generalization case : if we have n disk to move Move one disk from source to destination Move one disk from source to auxiliary needle. Move one disk from source to destination needle. Move one disk from auxiliary to destination needle. Move two disk from source to auxiliary needle. Move one disk from source to destination needle. Move two disk from auxiliary to destination needle. Move n-1 disk from source to auxiliary needle.General case Move one disk from source to destination needle.Base case Move n-1 disk from auxiliary to destination needle.General case

  16. towers(3,A,C,B) towers(2,A,B,C) step4 towers(2,B,C,A) towers step2 tower towers step6 tower (1,A,C,B) (1,C,B,A) (1,B,A,C) (1,A,C,B) step1 step3 step5 step7 A B C Start A B C A B C A B C step1 step2 step3 A B C step4 • Algorithm towers ( val disks <integer>, • val source <character>, • val dest <character>, • val auxiliary <character>, • ref step <integer> ) • recursively move disk from source to destination.. • Pre the tower consists of integer disks • source, destination, and auxiliary towers given • Post steps from moves printed • Print (“towers: ”, disks, source, dest, auxiliary ) • If (disks = 1) • 1 print (“step ”, step, “move from ”, source, “ to ”, dest) • 2 step = step + 1 • Else • 1 towers(disks – 1, source, auxiliary, dest, step) • 2 print (“step ”, step, “move from ”, source, “ to ”, dest) • 3 step = step + 1 • 4 towers(disks – 1, auxiliary, dest, source, step) • 4 End if • Return • End towers • The algorithm of towers of hanoi: • Towers call for three disks

  17. calls output tower (3,A,C,B) tower (2,A,B,C) tower (1,A,C,B) step1: Move from A to C step2: Move from A to B tower (1,C,B,A) step3: Move from C to B step4: Move from A to C tower (2,B,C,A) tower (1,B,A,C) step5: Move from B to A step6: Move from B to C tower (1,A,C,B) step7:Move from A to C • Tracing of Algorithm towers

  18. Summary of this chapter • There are two approaches to writing repetitive algorithms: iteration and recursion. 1. Recursion is a repetitive process in which an algorithm calls itself. 2. A repetitive algorithm uses recursion whenever the algorithm appears within the definition itself. • When a program calls a subroutine, the current module suspends processing and called subroutine takes over the control of the program. When the subroutine completes its processing and return to the module that called it, the module wakes up and continue its processing. • When control is returned to a calling module, it must know four pieces of information, which are stored in a stackframe: a. The values of parameters b. The values of local variables c. Where it should return when its processing is down d. The return value

  19. Summary of this chapter (Continue) • When a module calls a subroutine recursively, in each call, all of the information needed by the subroutine is pushed in the stackframe. The information is popped in the reverse order when subroutines are terminated one after another, and finally the control is returned to calling module. • A recursive algorithm has two elements: Each call either solves only part of the problem or reduces the size of the problem. • The statement that solves the problem is known as the base case: every recursive algorithm must have a base case. • The rest of the recursive algorithm is known as the general case. • The general rule for designing a recursive algorithm is as follows: a. First, determine the base case. b. Then, determine the general case. c. combine the base case and the general case into an algorithm.

  20. Summary of this chapter (Continue) • You should not use recursion if the answer to any of the following questions is no: a. Is the algorithm or data structure naturally suited to recursion? b. Is the recursive solution shorter and more understandable? c. Does the recursive solution run in acceptable time and space limits?

  21. Exercise • Consider the following algorithm algorithm fun1(x <integer>) 1 if (x<5) 1 return (3*x) 2 else 1 return (2*fun1(x-5)+7) 3 end if end fun1 What would be returned if fun1 is called as fun1(4) fun1(10) fun1(12)

  22. Homework • 设计一个递归算法求一个数组中的最大元素 • 设带头结点的线性链表中元素值为非零正整数,试写出 • 求线性链表中所有元素之和的递归函数(空表返回0) • 求线性链表中所有元素最大值的递归函数(空表返回0)

More Related