Big O: Worst Case Complexity

I am stuck trying to figure out/understand the worst case complexity of a function using Big O notation.

1
2
3
4
5
6
7
8
9
  int findEven (int a[], int n)
{
   int i = 0;
   while (i < n && (a[i] %2 != 0))
    {
       i++;
    }
   return i;
}    


I want to say that the worst case complexity of this loop is 2N because of the iterations of the while. I am unsure however of this though.

My thought process was that it is doing the while loop 2N times and i++ N/2 times so the worse case would be 2N. I have read a few things online, but they confused me more. Any help would be much appreciated.
you have n numbers in your array.
you loop through all of them and if one of them is even the loop quits

Therefore, the worst case is that you have to loop to the last element and your complexity increases linear with the amount of elements: O(N)

There is no O(2*N. complexety only tells you how the time increases with more elements. O(2*N) means that the time is linear with size and therefore is equivalent to O(N)
Thank you that makes better sense.

Another question is if the complexity looks to be based off of something other than N is it okay practice to put something like "O(str.size)"?

For example

1
2
3
4
5
6
7
8
9
10
 
string toLowerCase (string str)
{
  for (int i = 0; i < str.size(); ++i)
   {
        if (str[i] >= 'A' && str[i] <= 'Z')
        str[i] = str[i] - 'A' + 'a';
    }
  return str;
}


I would say that the worst case is O(str.size()) which is equal to O(N)? Because the loop is O(str.size()) and the condition is the size of the sting.

Thank you again for the help!
is it okay practice to put something like "O(str.size)"
nah, everything is dependent on the size, so this statement is not informative...
the complexity tells you how much influence the size has, that's what you want to know
So the worst case does not depend on how large something is it depends on how many passes it makes to complete something? So that second example would also be O(N) as well because it grows linearly with direct proportion to the size of the input sting size?
So the worst case does not depend on how large something is it depends on how many passes it makes to complete something?

I don't know what exactly you mean, sorry

So that second example would also be O(N) as well because it grows linearly with direct proportion to the size of the input sting size?

yep
Topic archived. No new replies allowed.