2

I have this recurrence:

T(n)= 2T(n/2) + (n-1)

My try is as follow:

the tree is like this:

T(n) = 2T(n/2) + (n-1)
T(n/2) = 2T(n/4) + ((n/2)-1)
T(n/4) = 2T(n/8) + ((n/4)-1) 
...
  • the hight of the tree : (n/(2h))-1 = 1 ⇒ h = lg n - 1 = lg n - lg 2
  • the cost of the last level : 2h = 2lg n - lg 2 = (1/2) n
  • the cost of all levels until level h-1 : Σi=0,...,lg(2n) n - (2i-1), which is a geometric series and equals (1/2)((1/2)n-1)

So, T(n) = Θ(n lg n)

my question is: Is that right?

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
Sosy
  • 109
  • 1
  • 2
  • 12

2 Answers2

3

No, it isn't. You have the cost of the last level wrong, so what you derived from that is also wrong.

(I'm assuming you want to find the complexity yourself, so no more hints unless you ask.)

Edit: Some hints, as requested

To find the complexity, one usually helpful method is to recursively apply the equation and insert the result into the first,

T(n) = 2*T(n/2) + (n-1)
     = 2*(2*T(n/4) + (n/2-1)) + (n-1)
     = 4*T(n/4) + (n-2) + (n-1)
     = 4*T(n/4) + 2*n - 3
     = 4*(2*T(n/8) + (n/4-1)) + 2*n - 3
     = ...

That often leads to a closed formula you can prove via induction (you don't need to carry out the proof if you have enough experience, then you see the correctness without writing down the proof).

Spoiler: You can look up the complexity in almost any resource dealing with the Master Theorem.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • cost of the last level = # of nodes * T(1) = 2^h where h= lg2n.. I don't know where is the wrong :S – Sosy Nov 29 '11 at 20:09
  • hmm I'm sorry, what 2^(lg n)? :$ – Sosy Nov 29 '11 at 20:43
  • 1
    @Sosy You wrote `lg2n` for the logarithm, I prefer to separate the function from the argument by a space. Since we deal exclusively with base-2 logarithms here, I omitted the base. – Daniel Fischer Nov 29 '11 at 20:47
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/5445/discussion-between-sosy-and-daniel-fischer) – Sosy Nov 29 '11 at 20:49
0

This can be easily solved with Masters theorem.

You have a=2, b=2, f(n) = n - 1 = O(n) and therefore c = log2(2) = 1. This falls into the first case of Master's theorem, which means that the complexity is O(n^c) = O(n)

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753