-1

I have this recursive algorithm and T(n) is the number of times that P(a, b) is executed and n := b - a

int foo[] = ... // array of big enough size
function P(int a, int b) 
    if (a+1 < b) {
       int h = floor((a+b)/2)
       if foo[h] >= 0 then P(a, h)
       if foo[h] <= 0 then P(h, b)
    }
end function

how can I compute T(1), T(2), T(3) and T(4)

OmG
  • 18,337
  • 10
  • 57
  • 90
skinnyBug
  • 289
  • 1
  • 3
  • 12
  • `h` is the midpoint between `a` and `b`. Therefore, both distances `[a, h]` and `[h, b]` have length `ceil(n/2)` (assuming `foo` is such that you always choose the bigger range). With that knowledge, you should be able to calculate the timings. – Nico Schertler Dec 28 '19 at 01:31
  • how did u get to the conclusion that they have length ceil(n/2) – skinnyBug Dec 28 '19 at 01:39
  • Ignoring the rounding, we could calculate `h - a = (a + b) / 2 - a = b / 2 - a / 2 = (b - a) / 2 = n / 2`. Same for the case `b - h`. – Nico Schertler Dec 28 '19 at 02:51

1 Answers1

1

As each time the distance between a and b (as an input of the function) is cut half, the time complexity is Theta(log(b-a)).

OmG
  • 18,337
  • 10
  • 57
  • 90