1

I calculate the optimal case complexity, average, and worst of this algorithm in java, I think if good is O (1) in the worst case is O (n), but I do not know if average! could you help me on how to calculate it? thank you!

public boolean searchFalse(boolean[] b){ 
 boolean trovato=false; 
  for(int i=0;i<b.length;i++){
   if(b[i]==false){
 trovato=true;
 break;
   }
  }return trovato;
}
2
  • 1
    n i.e. equal to the length of b. Commented Jan 9, 2013 at 10:45
  • Simple evaluation of the complexity of some implemented procedure is made by way of nesting loops. Commented Jan 9, 2013 at 12:17

5 Answers 5

6

I couldn't resist re-writing it

public boolean searchFalse(boolean[] bs){
    for (boolean b : bs) if(!b) return true;
    return false;
}

This stops after the first element potentially O(1).

If all the boolean are random the average search time is O(1) as you perform 2 searches on average, or if there is typically one false value in a random position the average is O(N)

If it has to search all the way, the worst case is O(N)

In short O(N/2) = O(N)

Sign up to request clarification or add additional context in comments.

3 Comments

True only if there is only one "false" in the array. If each value as the same probability to be true/false, we have a O(1). So the O(N/2) is wrong without assumptions.
@LoïcFévrier Good point. If the boolean are random the average time is O(log N)
Not O(log N) but O(1), specifically 2. One can use the formula sum(i*(1/2)^i, i=1..infinity) the probability to have to look at exactly K booleans beeing (1/2)^K (ie, true K-1 times and then false).
1

Complexity of algorithm is O(N).

If you need average amound of iterations it will be (1/1 + 1/2 + 1/4 +.. + 1/N) = (2 - 1/N) iterations expected if array with random booleans.

Comments

0

Average case will also be O(n)

Comments

0

Average case would be O(n) as worst case because its array iteration.

2 Comments

Could you explain better what you mean by "its the array iteration"? thanks!
you are iterating an array bs which always gives O(n) but here additional break may happen anywhere between 1-n or n/2 which becomes O(n/2) = O(n)
0

Because this is BOOLEAN array I thing average complexity would be constant O(1.5), worst O(n).

3 Comments

How is this linked with type of array?
Can you explain your answer a bit more? How is this related to the type of the array?
An average boolean array will have half of elements true, half of elements false. So in average we will find false in first or second element. If array would be for example of type double that would be different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.