How to find the time complexity of recursive methods in Java?

I can't fully grasp the concept of complexity. I want to know how to calculate it for method f (n) in this Code:

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    Random r = new Random();
    r.setSeed(System.currentTimeMillis());
    int n = r.nextInt(20) + 1;
    f(n);
  }

  private static void f(int n){
    if(n > 0){
      g(n);
      System.out.println();
      f(n-1);
    }
  }

  private static void g(int n){
    if(n > 0){
      System.out.print('X');
      g(n-1);
    }
  }
}

I know this is a recursive method, which puzzles me I see that every time I call the function f (), I call g () and run it n times, and then f () calls itself n-1 again until n = 0 I don't know where to start. Any help would be great thank you.

Solution

A common technique for determining the runtime of recursive functions is to write recursive relationships that describe the runtime as a number defined by itself Let's start with G If we let CN represent the running time of G (n), then we have

>C0 = 1 (calling g (0) requires a certain amount of work) @ h_ 502_ 11@> CN 1 = CN 1 (calling g (n) to perform a certain amount of work, and then calling g (n-1).

We can look at several values to see if we found a pattern:

> c0 = 1@H_502_11 @> c1 = c0 1 = 1 1 = 2@H_502_11 @> c2 = c1 1 = 2 1 = 3@H_502_11 @> c3 = c2 1 = 3 1 = 4

In general, it looks like CN = n 1 If you like, you can formalize this by inductive proof, but now we will accept it based on it This means that the running time of G is O (n)

Now let's make DN the runtime that calls f (n) Please note that

>D0 = 1 (call f (0) to perform a certain amount of work) @ h_ 502_ 11@> DN 1 = DN CN 1 (calling f (n 1) to invoke g (n 1), requiring CN 1 to work, and then calling f (n).

We can extend it to see if we see a pattern

> d0 = 1@H_502_11 @> d1 = c1 d0 = 2 1@H_502_11 @> d2 = c2 d1 = 3 2 1@H_502_11 @> d3 = c3 d2 = 4 3 2 1

In general, it looks like DN = n (n-1) (n-2)... 1 If you like, you can formalize it by induction This is a well-known sum, which applies to n (n 1) / 2 This quantity happens to be Θ (N2), so the whole running time is Θ (n2).

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>