0

new to computer science here, so i've wrote this bubble sort code and trying to calculate it's time complexity and performance here, the code for the sort is here:

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;
    }
  }
}

The swap method code is here:

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;
}

Now I know the bubble sort's time complexity is O(n^2) in worst-case performance, but I'm trying to calculate the function of each executions in my for loop here. I have a basic understanding of time complexity, i know a standard for loop is f(n) = 2n + 2 and we consider the worse case scenario for time complexity. So far, this is my thought progress to find the f(n) for my code:

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.

In the worst scenario, I'll have to use swap method every time, and since my time complexity for swap method is simply 8 (i think, it's only 8 executions right?) So the worst scenario for swap(current,current.next) is 8n?

If we add them up:

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

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

f(n) ~ O(n^2)

Is my time complexity f(n) correct?

If not, can you point me to the right answer please, also do you have some suggestions to improve on my code performance?

Khaled.K
  • 5,828
  • 1
  • 33
  • 51
zenoh
  • 2,071
  • 1
  • 22
  • 38

1 Answers1

0

As you have a while loop inside a for loop - yes, you have a O(n^2) complexity, which is considered bad.

The rule of thumb here is as follows (for N elements input, from better to worse):

  • No loops, just some executions regardless of the input size = O(1)
  • Loop(N/M) (you divide the input on each iteration) = O(log N)
  • Just one loop over N elements = O(N)
  • Loop2(N) inside Loop1(N) = O(N^2)

See this answer for better explanation: What does O(log n) mean exactly?

Community
  • 1
  • 1
phil_g
  • 516
  • 6
  • 13