Implementation of recursive algorithms C ++ and PHP for data structures and algorithms

Source: Internet
Author: User
Recursive algorithms of Data Structures and Algorithms C ++ and PHP implement recursive algorithms: they call their own algorithms directly or indirectly.

Implementation process: you can use a function or sub-process to complete recursive operations by directly or indirectly calling the code in a function or sub-process. (For a problem of the same category, the problem is converted into a subproblem of scale-down to a minimum problem with known conditions. then, the problem is solved and the result is returned step by step. It is actually a loop .)

Major manifestation: a small amount of code solves very complicated problems

Features:

1. recursion is to call itself in a method.

2. there must be a clear recursive termination condition called the recursive exit.

3. simple but inefficient, and generally not recommended

4. The return points and local variables of each layer are stored in stacks. Excessive recursion may cause stack overflow.


Instance 1: Factorial

C ++ code:

# Include
 
  
Int factorial (int n); int main () {using namespace std; int n; cout <"enter a number:"; cin> n; cout <n <"factorial:" <factorial (n) <
    
   

Running result:


Instance 2: numeric conversion


Code:

# Include
    
     
# Include
     
      
Void feelTheBase (char * s, int n, int sys); int main () {using namespace std; char s [60]; int n, sys; cout <"enter an integer:"; cin> n; cout <"Enter the hexadecimal type (, 16) to be converted ):"; cin> sys; feelTheBase (s, n, sys); cout <n <"converted to" <sys <"hexadecimal result:" <s <
        
       

Running result:



Example 3: list all subdirectories and files in a directory (it is also convenient to use the scandir function)

PHP implementation code:

        "; Rec ($ dir. '/'. $ file, $ lev+ 1);} else {echo str_pad ('', $ lev ,"--"). $ file."
";}} Closedir ($ dh) ;}$ dir ="./"; rec ($ dir) ;?>

Running result:

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.