-4

I am a student who is taking the programming class data structures and algorithms and I am in need of help with a exam question I cant seem to get a grip off.

Here is the problem:

Consider the following algorithm func on a given array A = {a1, a2, ..., an}:

  • If n = 1, then return.

  • If a1 > an, then exchange a1 and an.

  • Run func on {a1, a2, ... ,a2n/3}.

  • Run func on {an/3, a(n/3)+1, ... ,an}.

  • Run func on {a1, a2, ... ,a2n/3}.

Give a recurrence for the worst-case running time of this algorithm.

Here is a link to an image of the assignment if my explanation wasnt clear: https://i.stack.imgur.com/m3qNG.png

I understand that it is a divide and conquer problem but Im having a hard time to figure out how to solve it.

Thank you :)

Shaggy
  • 13
  • 3
  • 1
    So, the number of operations as a function of length can be expressed by the recurrence `T(n) = 3 T(2n/3) + 1`, with base case `T(1) = 1`. Is that enough to get you going? – Gassa Apr 30 '15 at 12:31
  • Hmm... sort of! But I dont really understand how {an/3, a(n/3)+1, ... ,an} becomes T(2n/3).. – Shaggy Apr 30 '15 at 12:49

1 Answers1

1
If a1 > an, then exchange a1 and an. 

this is a constant operation - so O(1)

Run func on {a1, a2, ... ,a2n/3}.

You invoke the array recursively on 2n/3 of it, so T(2n/3)

Run func on {an/3, a(n/3)+1, ... ,an}.
Run func on {a1, a2, ... ,a2n/3}.

Similar to the above, each one is T(2n/3)

this gives you total of T(n) = 3T(2n/3) + O(1), and T(1) = O(1).

Now, we can get a big O notation, using master theorem case 1:

log_{3/2}(3) ~= 2.7

O(1) is in O(n^2.7), so we can use the case, and get that T(n) is in

Theta(n^log_{3/2}(3)) ~= Theta(n^2.7)
amit
  • 175,853
  • 27
  • 231
  • 333
  • Wow, thats more advanced than I thougt it would be! Dont think we have been working with the master theorem case at all. Thank you for your help though! Could you explain why {an/3, a(n/3)+1, ... ,an} becomes T(2n/3)? – Shaggy Apr 30 '15 at 12:47
  • 1
    Because it contains 2n/3 of the elements, those with index `n/3,n/3+1 , ..., n-1,n`, and you invoke the function recursively on those 2n/3 elements. – amit Apr 30 '15 at 12:49
  • Okey thank you! So the worst case running time of this algorithm is Theta(n^2.7)? Will have to read up more on the master theorem case. – Shaggy Apr 30 '15 at 12:51
  • *approximately* Theta(n^2.7), it is actually `Theta(n^log_{3/2}(3))`. This is also the average case of the algorithm. – amit Apr 30 '15 at 12:54