Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - two conditions inside while loop time complexity

while( varz > equipmentNum || varz == 0 );

I have this piece of code and I want to measure its time complexity, but I am confused whether it will be Big O(n) or o(n^2) since it has two conditions inside it

question from:https://stackoverflow.com/questions/65928296/two-conditions-inside-while-loop-time-complexity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This depends on what is inside of the while loop, as well as what "N" represents in this example. Presuming N is "equipmentnumz" and no inner loops exist inside of the while, this is an O(n) algorithm.

By contrast, O(n)^2 would be a nested loop (e.g. a loop inside of another loop). Example:

while ($x < 1000): 
    while ($y < 1000): 
        y = y + 1
    x = x + 1

O(n) notation concerns itself with the behavior of how the algorithm handles increasing data sets. O(n) algorithms take exactly twice as long if the list size is doubled. The above example will take longer than twice as long if you double the list (in fact it will take many times longer). Because the iterations required are n^2, this is an O(n^2) algorithm.

What's O(n)?

O(n) algorithms scale linearly with the dataset. The following examples are both O(n).

# O(n) algorithm
while (number < 1000): 
    number = number + 1; 

# Example 2. Also O(n) 

while (number < 1000): 
    number = number * 2; 
    number = number / 2; 
    number = number + 1; 

Although the second example has more code and will take longer to execute, it will still only take exactly twice as long if you double the size of N. As a result, it is O(n), and the time required scales linearly with the size of the dataset.

The actual process of calculating O(n) is more complex than this post can adequately cover. This article has an excellent explanation with more information. (This page may also be helpful. It explains the concept/theory behind it in much simpler terms.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...