Nusha
Nusha

Reputation: 262

Recursive Formula

First, yes it's HW - really tried but not sure of something so ill be happy if you will help me:)

I have this code:

void func(int A[], int start, int n)
{
    int p = n/2;
    if ( 1 < n )
    {
        func(A, start, p);
        func(A, start + p, n-p);
        for (i=0; i<n; i++)
            cout << A[start+i];
    }
}

func(A, 0, n);

I need to give this code a recusive formula. What I did was - first recursion call is T(n/2). Second - this is the problem! really confuse with adding the 'p'...is that T(n/2) too?? Three - for is running on theta(n) and the outside recursion call is T(n)...

Can you help me get to the final formula??

Thanks

Upvotes: 0

Views: 499

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183868

If I read it right, you want the recurrence for the run time complexity.

For n > 1, you recur with parameter floor(n/2) and with parameter n-floor(n/2), and after that you output n items. Thus you have

T(n) = T(cost of first recursive call) + T(second rec. call) + extra work

which you should now bring into a form suitable to apply the master theorem.

Upvotes: 1

Thorn
Thorn

Reputation: 4057

This is either a trick question or you misread the question. What you have is a recursive formula. Do you need to switch this formula from C++ to more traditional math notation? Do need to find a non-recursive algorithm? In your answer to the question, what is T? The term formula does not really apply here because nothing gets computed. This is a void function that never modifies the given array. All that happens is some things elements from the array get put on the screen in some order.

I would start by tracing an example to understand what is going on. Lets say A = {1,2,3,4} Then 'func(A, 0,4)' is:

tracing func(A,0,4) :
p = 2
func(A,0,2)
func(A,2,2)
cout  << 1 2 3 4

tracing func(A,0,2) :
p = 1 //start=0; n=2
func(A,0,1)
func(A,1,1)
cout << 1 2

tracing func(A,2,2) :
p = 1 //start=2; n=2
func(A,2,1)
func(A,3,1)
cout << 3 4

tracing func(A,2,1) :
p = 0 //start=0; n=1
func(A,0,0)
func(A,0,1)
cout << 1

tracing func(A,3,1) :
p = 0 //start=3; n=1
func(A,3,0)
func(A,3,1)
cout << 3

tracing func(A,2,1) :
p = 0 //start=0; n=1
func(A,0,0)
func(A,0,1)
cout << 1

At this point I'm going to stop because this is your homework problem. You can finish it from here.

Upvotes: 0

Related Questions