Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solve: T(n) = T(n/2) + n/2 + 1

I struggle to define the running time for the following algorithm in O notation. My first guess was O(n), but the gap between the iterations and the number I apply isn't steady. How have I incorrectly defined this?

public int function (int n ) 
{
  if ( n == 0) {
    return 0;
  }

  int i = 1;
  int j = n ;
  while ( i < j ) 
  {
    i = i + 1;
    j = j - 1;
  }
  return function ( i - 1) + 1;
}
like image 671
sra Avatar asked May 05 '17 11:05

sra


People also ask

What is the solution to the recurrence t'n't n 2 )+ n?

this is a Geometric series with log(n) terms and each term gets halved. Hence answer is O(N).

What is the complexity of a recurrence relation T n 2T n 1 1?

Time Complexity =O(1).

What is the time complexity of T n )= t n 1 )+ n?

It is O(n^2) .


1 Answers

The while is executed in about n/2 time.

The recursion is executed passing as n a value that is about half of the original n, so:

n/2 (first iteration)
n/4 (second iteration, equal to (n/2)/2)
n/8
n/16
n/32
...

This is similar to a geometric serie.

Infact it can be represented as

n * (1/2 + 1/4 + 1/8 + 1/16 + ...) 

So it converges to n * 1 = n

So the O notation is O(n)

like image 111
Davide Lorenzo MARINO Avatar answered Nov 05 '22 22:11

Davide Lorenzo MARINO