With more Coding, recursive algorithms are very common. Recently I have been encapsulating tree structures, So recursive algorithms are even more indispensable. So let's talk about this recursive algorithm today and use java to implement a very classic recursive instance.
Recursive Algorithms are actually called by the program itself. It is manifested in a program that often encounters a coding policy that calls itself, so that we can use the thought of simplicity, this policy converts a large and complex problem into a small problem similar to the original one. In this way, we can see that we have solved a very large problem with a few statements, so the most important manifestation of the recursive policy is that a small amount of code solves very complicated problems.
We all know that the tree we encounter is an infinite tree, so we must use the loop and recursive algorithms to implement an infinite tree.
When making a recursive algorithm, you must grasp the exit, that is, the recursive algorithm must have a clear recursion termination condition. This is very important. In fact, this exit is a very understandable condition. When this condition is met, we will no longer recursion.
The following uses a java example to implement the recursive algorithm.
Problem description:
Java code list:
[Java]
Package com. cjq. filedown;
Public classFab {
Public static void main (String args []) {
System. out. println (fab (5 ));
}
Private static int fab (int index ){
If (index = 1 | index = 2 ){
Return 1;
} Else {
Return fab (index-1) + fab (index-2 );
}
}
}
Running result:
Program Analysis:
This is a very classic instance. It uses recursion to implement the Fibonacci series. The exit of this recursive algorithm is
[Java] view plaincopyprint?
If (index = 1 | index = 2 ){
Return 1;
}
In this Code segment, if the index of the program meets the condition, recursion will stop. So the running process of this program is:
After the program analysis, the implementation of recursion is complete. Readers can make a simple demo and feel the subtlety of this algorithm. In fact, many people are talking about the difficulty of the algorithm, making it difficult for them to get started, in fact, mastering the root of an algorithm is the most important. What is the root of an algorithm? Let's use this recursive algorithm. I feel that this root is the exit. If you find the exit, then the algorithm will naturally work.
Author: lfsf802