First, attach a small example of recursion and circulation.
public static void main(String[] args) { int recursion = recursion(1, 6, 0); int loop = loop(1, 6, 0); System.out.println("Output recursive result: + recursion); System.out.println("Output loop results: "+ loop); } /** * y>x,Sum and recursion of x+ (x+1) + (x+2) +... +y*@author LinWenLi * @date 2018August 31st, 9:05:24 a.m.*@param xInitial value of a plus*@param yMaximum plus value*@param sumInitial value of sum*@return int */ public static int recursion(int x,int y,int sum){ sum = sum + x++; if (x > y) { return sum; }else { return recursion(x, y, sum); } } /** * y>x,Find the sum (cycle) of x+ (x+1) + (x+2) +... +y.*@author LinWenLi * @date 2018August 31st, 9:05:24 a.m.*@param xInitial value of a plus*@param yMaximum plus value*@param sumInitial value of sum*@return int */ public static int loop(int x,int y,int sum){ for (; x <= y; x++) { sum = sum + x; } return sum; }
Recursion: Infinitely calling the function itself, each time a key variable is changed until the key variable reaches the boundary, it is no longer called.
.The difference between recursion and cycle is connection.
Same point:
(1)It is repeated by controlling the boundaries (or multiple) of a variable to change multiple variables in order to get the desired values.
(2)It’s all based on pre-designed inferences to achieve a certain value; (Note that loops are more process-oriented here than recursive bias results)
Different points:
(1)Recursion is usually the reverse thinking, “recursion” and “recursion” are not necessarily easy to find (more difficult to understand); and the loop from the start condition to the end condition, including intermediate loop variables, need to be expressed (more concise).
Simply put, recursion can be achieved with cyclic energy, but it can be achieved with recursion, and cyclic energy is not always possible. There are some questions: 1. only pay attention to the end of the cycle and the cycle process, and often this end condition is not easy to express (that is to say, the cycle is not easy to write); 2. only pay attention to the cycle of the orderNumber does not pay attention to the start condition and end condition of the cycle.
The time complexity and space complexity of the loop are better than that of recursion.
The advantage of recursion lies in its clarity and readability. It is more suitable for problems which are recursive in nature and difficult to solve by cycle. When the two are not difficult, it is generally preferable to use the cycle to solve the problem.