我的时间复杂度对我的冒泡排序代码是否正确?

时间:2015-03-12 02:03:29

标签: java algorithm sorting

这里是计算机科学的新手,所以我写了这个冒泡排序代码并尝试计算它的时间复杂度和性能,这里的代码就在这里:

for (int i = 0; i < size; i++)
{
  Node current = head.next;
  while (current.next != tail)
  {
    if (current.element.depth < current.next.element.depth)
    {
      swap(current, current.next);
    }
    else
    {
      current = current.next;
    }
  }
}

交换方法代码在这里:

void swap(Node nodeA, Node nodeB)
{
    Node before = nodeA.prev;
    Node after = nodeB.next;
    before.next = nodeB;
    after.prev = nodeA;
    nodeB.next = nodeA;
    nodeB.prev = before;
    nodeA.prev = nodeB;
    nodeA.next = after;
}

现在我知道冒泡排序的时间复杂度在最差情况下是O(n^2),但是我在这里试图计算我的for循环中每个执行的功能。我对时间复杂度有基本的了解,我知道循环的标准是f(n) = 2n + 2,我们考虑时间复杂度的最坏情况。到目前为止,我的思维进展是为我的代码找到f(n)

int i = 0;            This will be executed only once.
i < size;             This will be executed N+1 times.
i ++;                 This will be executed N times.
current = head.next;  This will be executed N times.
current.next != tail; This will be executed N times.

And since a while loop is within the for loop,
    it's n*n within the while loop, there
    are 4 operations, so it's 4n^2.

在最糟糕的情况下,我每次都必须使用交换方法,因为我的交换方法的时间复杂度只是8(我认为,它只是8执行权?)所以swap(current,current.next)的最差情况是8n

如果我们将它们添加起来:

f(n) = 1 + n + 1 + n + n + n+  4n^2 + 8n

f(n) = 4n^2 + 12n + 2

f(n) ~ O(n^2)

我的时间复杂度f(n)是否正确?

如果没有,请指点我正确的答案,你也有一些改进我的代码表现的建议吗?

1 个答案:

答案 0 :(得分:0)

因为你在for循环中有一个while循环 - 是的,你有一个O(n ^ 2)的复杂性,这被认为是坏的。

这里的经验法则如下(对于N个元素输入,从好到坏):

  • 没有循环,只是一些执行,无论输入大小= O(1)
  • 循环(N / M)(在每次迭代时划分输入)= O(log N)
  • N个元素上的一个循环= O(N)
  • Loop1(N)内的Loop2(N)= O(N ^ 2)

请参阅此答案以获得更好的解释:What does O(log n) mean exactly?

相关问题