'What is the time complexity of while loops?
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++;
}
Solution 1:[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).
(More details below)
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)
).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |