0

I am a little confused as to what the big O notation for a method like such would be

public void printOut (SinglyLinkedList<Double> myLinked){
Iterator<Double> itr = myLinked.iterator();
while (itr.hasNext()){
    double d = itr.next(); // unboxing
    if (d > 5.0)
    System.out.println (d);
} // while
} // method printOut

If there was no if statement I know it'd be 'n' but since the println wouldn't be executing every time it iterates, how do I come up with the notation?

ThomasJazz
  • 99
  • 9

4 Answers4

2

The answer is still O(n)

If the loop runs through the list, it is O(n)

LINGS
  • 3,560
  • 5
  • 34
  • 47
2

You're still iterating through the entire list and looking at each value for the comparison, so the program is still O(n).

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

do yourself a favor, for each line, type in how many time that line executes. Do this first by removing the while loop and then with the while loop. You would find a patter and you would be able to understand it better.

In simple terms, an if is basically a constant complexity i.e., O(1) which wouldn't add anything to the outer loop. Your wile will give you O(n) and rest of teh statements will give you O(1), O(1) and O(1) respectively. In the end it will be O(n) + O(1) + O(1) + O(1) ... which would result in O(n) overall complexity.

Em Ae
  • 8,167
  • 27
  • 95
  • 162
0

The loop iterates n times and at each step it checks the if condition.If the condition is true it executes the if statement which takes constant time. Since there is not effect of constant time on the overall complexity,it would still be O(n).

Sai Raman Kilambi
  • 878
  • 2
  • 12
  • 29