What is the time complexity of while loops?

不问归期 提交于 2020-02-03 04:53:04

问题


I'm trying to find the time complexity of while loops and I have no idea where to begin. I understand how to find the complexity class of for loops, but when it comes to while loops, I get completely lost. Any advice/tips on where to begin?

Here is an example of a problem:

x = 0;
A[n] = some array of length n;
while (x != A[i]) {
   i++;
}

回答1:


When you gotta do something n times, you have to do it n times. You can use a for loop, a while loop or whatever that your programming language (or pseudo code!) offers. Crudely, big O notation comments on the amount of work you have to do, and doesn't care about how you do it (somewhat less crudely, it comments on how the amount of work that needs to be done grows with the growing input).

Keep reading for the details.


I think you are confusing things here. for and while are programming language constructs to express operations that are to be repeated.

Algorithm analysis is agnostic of the language of implementation, and doesn't care about the actual constructs you use while expressing the algorithm.

Consider following:

1. Input n
2. Do OperationX n times

The Big O notation machinery helps you in commenting on the complexity of the above operation. This helps in many cases. For example, it can help you in comparing the runtime of the operation above with the following:

1. Input n
2. Input m
3. Repeat m OperationX n times.

The Big O notation will tell you that the former is O(n) and the latter is O(m * n) (assuming OperationX takes a constant time).

You can write the code using the loop construct of your choice, it doesn't matter.

for(int i = 0; i < n; i++) {
    operationX;
}

Is the first operation, and

i = j = 0;
while(i < n) {
    j = 0;
    while(j < m) {
      operationX;
      j++;
    }
    i++;
}

the second. The big O notation doesn't really care if the for and while was switched.


A[n] = some array of length n;
for(x = 0;x != A[i];i++) {

}

Is a for re-write of your question with the same complexity (O(n)).



来源:https://stackoverflow.com/questions/33637125/what-is-the-time-complexity-of-while-loops

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!