Why to use Recursion carefully when using Java to implement algorithms
This article shows you why use Java implementation algorithm with caution recursion, concise and easy to understand, absolutely can make your eyes shine, through the detailed introduction of this article I hope you can gain something.
Phenomenon:
Recursion is a very classic algorithm we achieve, can be a good description of the principle of an algorithm! Recursion is a good choice for algorithm description, performance and code structure understanding!
But what this article wants to say is that java to achieve a recursive algorithm, try not to use recursive implementation, but converted to non-recursive implementation.
Recently, when implementing a more complex algorithm, I tried it, and the non-recursive implementation can improve the speed by 1/3 compared to the recursive implementation.
Take the following simple example: (Note: For simplicity of description, only a simple example is used here)
Input parameter: N
Output result: log1 + log2 + log3 +...+ logN
The two implementation codes are as follows:
Java code
package test; public class RecursiveTest { /** * recursive implementation * * @param n * @return */ public static double recursive(long n) { if (n == 1) { return Math.log(1); } else { return Math.log(n) + recursive(n - 1); } } /** * nonrecursive realization * * @param n * @return */ public static double directly(long n) { double result = 0; for (int i = 1; i