Search code examples
loopsbig-ocomplexity-theory

While loop, for loop, flag and complexity


If I have a for loop to search something, and it is encased by a while loop, then is it O(N^2) despite never running the while loop twice? For example, searching for 6 in a collection

int location;
while (found == false AND quit == false)
    foreach data x in collection
        if x == 6
            location = 6
            found = true // exit prematurely
         end if
    end for
    quit = true // exit here after for loop
end while

What is the complexity of this algorithm?


Solution

  • No, it is not O(N^2). Big-O describes the worst-case scenario for Your algorithm. Consider what is the worst case in this case. If You are trying to find number 6 is a collection of ints then the worst case is when it's not there obviously.

    So, if Your number is not there, You would iterate over the whole list in a foreach and then finish no matter what.

    So, the Big-O of this code is actually O(N).

    The use of while in here is simply incorrect.