Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My answer is going to focus on methodology since that's what the explicit question is about. For the answer to this specific problem see others' answer such as amit's.</p> <p>When you are trying to evaluate complexity on algorithms with recursion, you should start counting just as you would with an iterative one. However, when you encounter recursive calls, you don't know yet what the exact cost is. Just write the cost of the line as a function and still count the number of times it's going to run.</p> <p>For example (Note that this code is dumb, it's just here for the example and does not do anything meaningful - feel free to edit and replace it with something better as long as it keeps the main point):</p> <pre><code>int f(int n){ //Note total cost as C(n) if(n==1) return 0; //Runs once, constant cost int i; int result = 0; //Runs once, constant cost for(i=0;i&lt;n;i++){ int j; result += i; //Runs n times, constant cost for(j=0;j&lt;n;j++){ result+=i*j; //Runs n^2 times, constant cost } } result+= f(n/2); //Runs once, cost C(n/2) return result; } </code></pre> <p>Adding it up, you end up with a recursive formula like <code>C(n) = n^2 + n + 1 + C(n/2)</code> and <code>C(1) = 1</code>. The next step is to try and change it to bound it by a direct expression. From there depending on your formula you can apply many different mathematical tricks.</p> <p>For our example: </p> <p>For <code>n&gt;=2</code>: <code>C(n) &lt;= 2n^2 + C(n/2)</code></p> <p>since C is monotone, let's consider <code>C'(p)= C(2^p)</code>: <code>C'(p)&lt;= 2*2^2p + C'(p-1)</code></p> <p>which is a typical sum expression (not convenient to write here so let's skip to next step), that we can bound: <code>C'(p)&lt;=2p*2^2p + C'(0)</code></p> <p>turning back to <code>C(n)&lt;=2*log(n)*n^2 + C(1)</code></p> <p>Hence runtime in <code>O(log n * n^2)</code></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload