递归插入排序的运行时间的递归

时间:2011-09-07 16:47:14

标签: c relation recurrence insertion-sort

目前,我被分配编写插入排序算法的递归版本。我做到了。事实上,这就是:

void recursiveInsertionSort(int* inputArray, int p, int q)
{
  while (q > p)
  { 
     recursiveInsertionSort(inputArray, p, q-1);
     if (inputArray[q-1] > inputArray[q])
     {
         int temp = inputArray[q];
         int temp2 = inputArray[q-1];
         inputArray[q] = temp2;
         inputArray[q-1] = temp;
         q--;
     }
  }
}

我的问题是双重的。首先,我不确定我提出的复发关系是否正确。我想出了

T(n) = T(n-1) + T(n^2) 

作为我的复发关系。是对的吗?我在那之间蹦蹦跳跳,只是

T(n) = T(n^2)

其次,我应该使用代数来证明

f(n) = ((n+1)n / 2) 

解决了递归关系。我真的很难做到,因为A.我不确定我的复发是否正确而B.我有时会对数学很糟糕。

对任何问题的任何帮助将不胜感激。

感谢。

好吧,我在数学教授的帮助下成功解决了这个问题:P我要把它留在这里,以便其他人知道如何去做。有人应该将其复制为答案:D

所以这个的递归关系应该是T(n)= T(n-1)+ n而不是我原来的,这是主要的问题。为什么?那么它是执行n-1的递归反向传输所需的时间,因为如果你要去n,你将只有一个元素,并且这是一个arleady排序。加上一次插入或一次实际排序所需的时间。

这就是n的原因是因为当你到达那里时,你正在检查一个数字,而不是每个数字,这恰好是n次。

现在,您如何证明函数f(n)解决了T(n)?

我们知道f(n)解决了T(n)。这意味着你可以这样做:

We know that f(n) is equal to (n(n+1))/2 . So if T(n) is equal to T(n-1) + n, that means we take away 1 from every n in f(n) and then plug that into T(n).

That gives us T((n+1-)n-1)/2)) + n . That simplifies to T((n(n-1)/2) + n. Take that + n thats out there and multiply it by 2/2 to be able to have it all over a common denominator. Giving you (n^2 - n + 2n)/2 . Simplifies down to ((n^2) + n)/2 which further simplifies to, if you factor out an n, (n(n+1))/2. Which is f(n).

呜!

0 个答案:

没有答案