J2SE Fast Advanced--recursive algorithm

Source: Internet
Author: User

        Recursive algorithm

Recursive, Baidu Encyclopedia is defined as: The program calls its own programming skills. To be blunt is a function or procedure that invokes itself when executed.

Let's start with an example of "factorial of a number" to illustrate:

public class Test {public static void main (string[] args) {System.out.println (Method (3));} public static int Method (int n) {if (n==1) return 1;elsereturn N*method (n-1);}}
It is known from the program that the method () function is to calculate the factorial of the parameter n, when the value of n is 1 o'clock, the direct return result is 1; otherwise execute the statement under Else, call the method () function, the period execution process is as follows:

When N=3 is executed, the return 3*method (2) under else is performed, and method (2) calls the function method () itself with 2 as the argument, and, similarly, executes the return 2*method (1) of the other when n=2, n=1, Returns 1 directly.

Here you will find that recursion can transform a large, complex problem layer into a smaller problem than the original problem to solve, only a small amount of program code can be described in the process of solving the problem of multiple repeated calculations, greatly reducing the code of the program.


Recursion has the following characteristics:

1, recursive implementation, is to transform a problem into a similar size of the problem, and this new problem is the same as the solution of the original problem, just deal with the object is different, through multiple recursion to derive the simplest solution, and then go back to the layer by level return call, get the final solution. ;

2, recursion to have an end condition, used to terminate the loop call, that is, when the condition is satisfied, it is no longer recursive, otherwise always call itself, know to satisfy this bar. (The IF (n==1) in the example above is the end condition)

3. Although recursion to some extent make the Code reach reuse, but In -depth recursion involves frequent stack-out and allocating memory space, so the efficiency is low, and when the problem is large, it is not recommended.

4, in the recursive process, the parameters in each call, method return point, local variables are stored in the stack, if the problem is very large, it is easy to cause a stack overflow.

examples of recursive implementations

For a deeper impression, here are a few small examples that can be implemented with recursion

1, to seek 1+2+3+......+100 and    

public class Sum {public static void main (string[] args) {System.out.println (sum (100));} public static int sum (int num) {        if (num <= 0) {        return 0;                When Num=0, the loop ends                   }else{        return num + sum (num-1);//Call recursion method         }      }    
2, the decimal number is converted into binary number
public class Decimaltobinary {public static void main (string[] args) {decimaltobinary (118);} public static void decimaltobinary (int num) {        <span style= "white-space:pre" ></span>if (num ==0) {                    / /When num=0, loop over               <span style= "White-space:pre" ></span>       return;       <span style= "White-space:pre" ></span>        }else{                      decimaltobinary (NUM/2);  Call the Recursive method                      System.out.print (num%2);       <span style= "White-space:pre" ></span>}}  
3. Calculate the Fibonacci sequence
public class Fibonacci{public static void Main (string[] args) {System.out.println (FIB (4));}   static int fib (int n)  {     if (n==0| | n==1)         return n;         else         return fib (n-1) +fib (n-2);  }  }


The difference between recursion and iteration

Some beginners may sometimes confuse the two algorithms of recursion and iteration, where recursion is a function (or process) that, through constant invocation of itself, obtains the final result, and the iteration can be seen as a loop.

The examples at the beginning of the article can be implemented in iterations as follows:

public class Test {public static void main (string[] args) {System.out.println (Method (3));} public static int Method (int n) {int product=1;for (int i=n;i>0;i--) {product=product*i;} return product;}}

from the code can be found that the iteration is only a simple loop, from I=n to I=1, and finally directly return to the final Solution product; recursion is the problem that needs to be solved in a similar scale, the simplest solution is obtained by multiple recursion, and then the final solution is obtained by returning the call from layer to row. Here recursion is like we climb a hill, a step to climb to the top of the mountain, and finally to a step down a step down the same principle.



J2SE Fast Advanced--recursive algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.