4

Could you explain how to find time complexity of the folowing code? Any help appreciated.

int boo(n) {
    if (n > 0)
    {
         return 1 + boo(n/2) + boo(n/2);
    }
    else 
    {
         return 0;
    }
}
Yazgan
  • 111
  • 9
  • This could help you http://stackoverflow.com/questions/13467674/determining-complexity-for-recursive-functions-big-o-notation – Daniel Corzo Nov 29 '16 at 16:04
  • @DanielCorzo Thank you Daniel, I've already seen that. The situation here is a bit different. – Yazgan Nov 29 '16 at 16:07

1 Answers1

1

enter image description here

Sometimes it is good to write it down. When you start, it sum 1 + boo(n/2) + boo(n/2), which is on the second line.

And each of that n/2 is run also

etc. etc.

So at the end, while the number of calls is growing exponencially, the number of repetions is only logharitmic, which at the end remove each other and you got O(N).

PS : It is enough to count down the last line, the whole tree has always only once time more nodes (minus one), which in complexity theory is neglible (you dont care about constants, which multiplicating by two is)

libik
  • 19,204
  • 9
  • 35
  • 72
  • This exact question comes in exam LOL thanks again @libik – Yazgan Dec 01 '16 at 09:34
  • :D:D:D yeah, you are right. Actually that is exact binary tree traversing, I remembered it when I see your answer was same with binary tree traverse complexity. So no doubt. – Yazgan Dec 01 '16 at 09:36