1

Given a sequence of n integers, A. To find the sum of the sequence we are following the following recursive algorithm, we make a new sequence B of size n/2 where B[i] = A[2*i] + A[2*i + 1] for i from 0 to n/2 - 1 and we replace A with B. When size of A is 1, we return the element itself.

Shouldn't the time complexity be calcualted as follows?

T(n) = T(n/2) + O(n/2)
or
T(n) = T(n/4) + O(n/4) + O(n/2)
or
T(n) = O(1) + O(2) + O(4) + ... + O(n/4) + O(n/2)

At this point I am not sure if I am doing it correctly and what this value should be equal to. I am assuming O(nlgn)

How do I arrive at the solution ? Also, using master theorem is giving me O(n), I am not sure if I am applying master theorem properly. Can someone please guide me here?

1
  • It's not clear exactly what your "algorithm" is, but note that if summing a sequence takes longer than O(n), you're doing something wrong ;) Commented May 15, 2017 at 8:29

1 Answer 1

5

First observe that

O(1) + O(2) + O(4) + ... + O(n/4) + O(n/2) =
  O(1 + 2 + 4 + ... + n/4 + n/2)

Then you could recognize here the sum of a geometric progression. Assuming n = 2^m (2 to the power of m)

  1 + 2 + 4 + ... + 2^(m-2) + 2^(m-1) = 2^m = n

Therefore your method gives you T(n) = O(n). This is in an agreement with the master theorem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.