简体   繁体   English

递归公式

[英]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). 我所做的是-第一次递归调用是T(n / 2)。 Second - this is the problem! 第二-这是问题! really confuse with adding the 'p'...is that T(n/2) too?? 真的与加'p'相混淆...也是T(n / 2)吗? Three - for is running on theta(n) and the outside recursion call is T(n)... 三-for在theta(n)上运行,外部递归调用为T(n)...

Can you help me get to the final formula?? 您能帮助我得出最终的公式吗?

Thanks 谢谢

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. 对于n > 1 ,使用参数floor(n/2)和参数n-floor(n/2) ,然后输出n项目。 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. 您现在应该将其转换为适合应用主定理的形式。

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? 您是否需要将此公式从C ++切换到更传统的数学符号? Do need to find a non-recursive algorithm? 是否需要找到非递归算法? In your answer to the question, what is T? 在回答问题时,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: 假设A = {1,2,3,4}那么'func(A,0,4)'是:

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. 您可以从这里完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM