Code 1
int i = 0;
int j = 0;
while(i < n){
while(j < n){
printf("{%d,%d}",arr[i],arr[j]);
j++;
}
i++;
j = 0;
printf("\n");
}
Code 2
int result = 0;
int i = 0;
while (i < n / 2){
result += arr[i];
i += 1;
while (i >= n / 2 && i < n){
result += arr[i];
i += 1;
}
}
printf("%d\n", result);
I only know how to find time complexity with for loops, but I am uncertain about while loop. It would be greatly appreciated if someone could help me find the total running time of each code.
The first code sample is pretty much a classis for loop. Its complexity is O(n^2). This is because the inner loop has a complexity O(n) and it is run n times.
The second one is a bit more difficult, untill you see that is equivalent to a non nested loop (ignoring the complexity of the checks)
int result = 0;
int i = 0;
while (i < n){
result += arr[i];
i += 1;
}
printf("%d\n", result);
meaning its complexity is O(n)
The best approach to calculating time complexity is trying to actually understand how the algorithm works and counting the operations. In the second example, the inner loop never runs untill the outer loop is at its last iteration. And since they even execute the same code, the whole thing can be reduced to one loop.
Another good example is this:
for(i=0;i<n;i++){
for(j=i;j<n;i++){
//do something
}
}
Let's count the operations: 1 + 2 + 3 + 4 + ... + n. This comes down to n*n/2 leading to O(n^2)
A for loop, at the end of the day, IS a while loop. Something of the form:
for(int i=0; i<n; i++)
is equivalent to:
int i=0;
while(i<n)
{
i++;
}
In fact in pure mathematical analysis of algorithms you are supposed to make any for loop into a while loop in your algorithms (there are a couple reasons why).
Going back to your code. The analysis is simple:
The outer loop runs at most n times.
Before the iteration of any loop the value of j is 0.
Informally: we can tell before any iteration of the inner loop the value of j is 0.
Inside the inner loop the only statement that updates j is j++.
The inner loop runs at most n times by the loop guard.
The outer loop runs at most n times, the inner loop runs at most n times for every iteration of the outer loop. All other statements are constant. The algorithm is in O(n*n)=O(n^2)
The second one is slightly more convoluted but:
The algorithm thus runs O(n/2+n/2) = O(n) times
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.