One
Method can call itself (if you are surprised by the notion of recursion, complete the practice 1.1.16 to practice 1.1.22). For example
Another implementation of the rank () method of BinarySearch is given below. We will often use recursion because the recursive code is more than
The corresponding non-recursive code is more concise, elegant and easy to understand. The comments in this implementation are a concise illustration of how the code works.
We can use the mathematical induction method to prove the correctness of the algorithm explained by this note. We will start this topic in section 3.1 and
Two-point lookup provides one such proof.
The following three points are the most important when writing recursive code.
? Recursive which comes has one of the simplest cases-the first statement of a method is always a conditional statement that contains a return.
? Recursive invocation always tries to solve a smaller sub-problem so that recursion can converge to the simplest case. Next
, the difference between the fourth parameter and the third parameter has been shrinking in the code for a polygon.
There should be no intersection between the parent of the recursive call and the child problem that is trying to resolve. In the following code, two sub-issues are
The array part of the self-operation is different.
1 Public Static intRankintKeyint[] A,intLointhi) { 2 //if key exists in a[], its index will not be less than lo and will not be greater than hi3 if(Lo > Hi)return-1;4 intMid = lo + (Hi-lo)/2;5 if(Key < A[mid])returnRank (key, A, lo, mid-1);6 Else if(Key > A[mid])returnRank (key, a, Mid + 1, HI);7 Else returnmid;8}
Violating any of these can result in incorrect results or inefficient code (see Practice 1.1.19 and Practice 1.1.27), while
Adhering to these principles can produce clear, correct, and easy-to-evaluate performance programs. Another reason to use recursion is that we can use several
Model to estimate the performance of the program. We'll look at the two points in section 3.2 and several other places to analyze the problem.
Algorithm Sedgewick Fourth Edition-1th chapter BASIC-001 recursion