1. Basic idea of recursive algorithm:
Java recursive algorithm is a recursive algorithm based on Java language implementation. Recursive algorithm is an algorithm that directly or indirectly calls its own function or method. The essence of recursive algorithm is to decompose the problem into the sub-problem of the similar problem of scale reduction, and then recursive call method to express the solution of the problem. Recursion often brings us very concise and very intuitive code forms, which makes our coding much simpler, yet recursive thinking is indeed contrary to our conventional thinking, usually from the top down thinking problems, and recursive trend from the bottom up thinking.
2. The recursive algorithm solves the problem characteristic:
- Recursion is the method that calls itself.
- When using a recursive strategy, there must be a definite recursive end condition called a recursive exit
- Recursive algorithm code is very concise, but the recursive algorithm is less efficient in solving problems. Therefore, recursive design procedures are not advocated.
- In the process of recursive invocation, the system opens up stacks for each layer's return point, local quantity, etc. Too many recursive times can cause stack overflow, etc., so generally do not advocate the use of recursive algorithm design program.
In the recursive algorithm, must grasp the export, that is, to do recursive algorithm must have a definite recursive end condition. This is very important. In fact, this export is a condition, when we meet this condition, we will no longer recursion.
3. code example:
| 12345678 |
publicclassFactorial { //this is a recursive function intfact(intn){ if(n==1) return1; returnfact(n-1)*n; } } |
| 123456789 |
publicclassTestFactorial { publicstatic voidmain(String[] args) { // TODO Auto-generated method stub Factorial factorial=newFactorial(); System.out.println("factorial(5)="+factorial.fact(5)); }} |
The code execution flowchart is as follows:
In this program n=5 is the exit of the program.
Java Recursive algorithm