Question

Consider the following: Algorithm 1 Smallest (A,q,r) Precondition: A[ q, ... , r] is an array...

Consider the following:

Algorithm 1 Smallest (A,q,r)

Precondition: A[ q, ... , r] is an array of integers q ≤ r and q,r ∈ N.

Postcondition: Returns the smallest element of A[q, ... , r].

1: function Smallest (A , q , r)

2: if q = r then

3: return A[q]

4: else

5: mid <--- [q+r/2]

6: return min (Smallest(A, q, mid), Smallest (A, mid + 1, r))

7: end if

8: end function

(a) Write a recurrence relation which describes the time complexity of this program in terms of the size of array A. Note that the size of the array A is r−q + 1. Suppose n = r−q + 1.

(b) Using the master theorem, give a Θ (theta) bound on the complexity of this program.

(c) Write a non-recursive version of Smallest(A,q,r) (in pseudo-code).

(d) Find the worst case running time of this new program and express it in Θ (theta) notation.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

(a) In the given function, the recurrence relation is T(n)=2*T(n/2) + C. This is because when an array with size n is given to the function, it divides the task into 2 parts each dealing with array of half the size n/2. And it also performs some other operations which take some constant time C.

So, total time T(n)=2*T(n/2) + C.

(b) The master theorem works only for following type of recurrences or for recurrences that can be transformed to following type:

T(n) = aT(n/b) + f(n) where a >= 1 and b > 1

Our recurrence is like this with a=2, b=2 and f(n)=constant.

f(n) can also be written as Θ(1) or Θ(n0).

According to master's theorem, If f(n) = Θ(nc) where c < Logba then T(n) = Θ(nLogba) (here c=0 and Logba=1 as a=b=2), so we have our time complexity T(n)=Θ(n1)=Θ(n).

So, time complexity is Θ(n).

(c) function Smallest (A , q , r)

1. small <-- A[p] //initialising small with first element of array

2. For each element i in A //comparing each element of array with small

if A[i] < small then //if A[i]<small then assign A[i] to small

small=A[i];

endif

endfor

3. return small //returning small

(d) As the program traverses the complete array one time only, so the time complexity is \Theta (n) where n is the number of elements in the array.

Add a comment
Know the answer?
Add Answer to:
Consider the following: Algorithm 1 Smallest (A,q,r) Precondition: A[ q, ... , r] is an array...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT