简体   繁体   中英

Run Time Of Nested While Loop That Doesn't Reset

Would the following code be O(n^2) or O(n)?

int i=0, j=0;
while (i < n) {
  while (j < n) {
    j++;
  }
  i++;
}

Since the inner while loop only runs once from 0 to n I would imagine it's equivalent to having two separate while loops thus the total run-time would be O(2n).

It is O(n) in this particular pieces of code . Eg If n=10 for i=0 inner loop executes from j=0 to j=9(10 times ) and for i = 1 to 9 inner loop exeutes 0 times , (since j(10) >n(10) will never become true), So total time = 10 times outer + 10 times inner = 20= 2n Hence time complexity is O(n)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM