0

I am having trouble understanding Big-O notation. How do I find the Big-O and worst case running time of this function?

I wrote this function to reverse the order of a doubly linked list.

public void reverse() {
    Node<T> temp = head;
    Node<T> current = head.next;
    head.next = null;
    head.previous = current;

    while(current != null)
    {
        Node<T> next = current.next;
        current.next = temp;
        current.previous= next;
        temp = current;
        current = next;
    }
    head = tail;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Big-O specifies how the running time increases with respect to the input increasing. For example, if your input size increases `k` times, and your running time increases by a polynomial of degree 2, that would be an `O(n^2)` algorithm. For small inputs Big-O is rather useless, as the other factors that affect running time are not negligible. – RaminS Jan 24 '19 at 01:49

2 Answers2

2

Look for the number of nested loops.

Since there isn't one it's just O(n) because there's no geometric reduction of the n over the course of the loop

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
0

The "data structure" should remind us of a "doubly linked list", and assuming a list of size n, this algorithms reverses the order of the list. We can count now the (compare, assign, mathematical) operations, which this algorithm will accomplish (besides, whether it is correct & terminates) ..in relation to n:

And we will find, that this algorithm does (in worst, best & average (so every)) case:

4 assign statements:
 Node<T> temp = head;
 Node<T> current = head.next;
 head.next = null;
 head.previous = current;
n + 1 compare statements:
 while(current != null)
(lets not count the braces))
n * 5 assign operations:
 Node<T> next = current.next;
 current.next = temp;
 current.previous= next;
 temp = current;
 current = next;
and 1 last assign operation
 head = tail;

so it is 4 + n + 1 + 5 * n + 1 = 6 * n + 6 (assign or compare ... but compare are the "most expensive" ones in terms of run time) operations. We eliminate constant factors and offset (since they can be neglected, when ngets big...and due to exact mathematical rules, we learned), and get:

6n + 6 = O(n)

..and apropos: it is correct & terminates! ;)

xerx593
  • 12,237
  • 5
  • 33
  • 64