"Java" java_19 recursive algorithm

Source: Internet
Author: User

1. Recursive algorithm

A method called the B method, we are easy to understand! Recursion is:a method calls a Method! is to call yourself, so when designing a recursive algorithm, be sure to indicate when you don't call yourself. Otherwise, it's a dead loop!

1.1 main points of recursive algorithm

recursion is a common method of solving problems, which is to simplify the problem gradually. The basic idea of recursion is to " call yourself ", and a method that uses recursion technology will call itself directly or indirectly.

Recursion can be used to solve some complex problems with simple programs. For example: Most sorts use recursive algorithms.

1.2 Recursive structure

The recursive structure consists of two parts:

1. define the recursive header. Answer: When not to call its own method. If there is no head, it will fall into a dead loop.

2. recursive body. Answer: When to call your own method.

2. Code hinting
 Packagecom.oliver.test;
Public classtestrecursion {Static intA = 0; Public Static voidtest01 () {a++; System.out.println ("Recursive" +a+ "Times"); if(a<=10) {//Recursive Headertest01 (); } Else{//Recursive bodySystem.out.println ("recursion ends! "); } } Public Static inttest02 (intN) { //Ask for factorial! if(n==1){ return1; } Else { returnn*test02 (n-1); } } Public Static voidMain (string[] args) {//Call test01test01 (); intValue = test02 (3); SYSTEM.OUT.PRINTLN ("Factorial result is:" +value); }}
3. Printing results

Recursion 1 times
Recursion 2 times
Recursion 3 times
Recursion 4 times
Recursion 5 times
Recursion 6 times
Recursion 7 times
Recursion 8 times
Recursion 9 times
Recursion 10 times
Recursion 11 times
Recursion ends!
Factorial results are: 6

"Java" java_19 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.