简体   繁体   中英

Time complexity of while loop when bound is reset?

I have a while loop that iterates through an array using the index "i" and only performs O(1) operations. If perhaps the bound j is decremented to compare an element at j with the current element at i, I want to be able to continue iterating through the array if j < i, but i does not equal the length of the array - 1. If I reset j to its initial bound of length of array - 1, would the while loop still be O(n) complexity?

Example (in Java):

i = 0;
j = array.length - 1;

while(i < j) {

  ...

  if (j < i) {

    j = array.length - 1;

  }

  i = i + 1;

}

This is because the condition j < i is never true (at least not for an array length which is greater than zero).

Imagine you start with j = 1, then you have only one iteration, where i's value is only incremented one time, causing the expression i < j to evaluate to false in the next iteration (i's value is 1 here) and therefore breaking the loop.

This applies for any case higher than j = 1 as well (unless overflow).

And another hint for university stuff: Just try it out. Either by going through it by hand or by adding println calls to the source code. It's much easier to do by example than by overthinking abstract numbers.

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