简体   繁体   中英

How do I calculate time complexity when having a break statement

void F ( int a[], int n ) { // args: array a[ ] of size n
   for ( int k = n/2; k>0; k/=2 ) {
     for ( int j = 0; j< n; j++ ) {
       if ( a[j] >= a[k] ) break;
       else { int m = a[j]; a[j] = a[k]; a[k] = m; }
}}}

Now, The first for loop is 2 + log base-2 of n (2 + 2nd loop) . So that's that.

The second (nested) loop is a problem. If this is a best/worst case scenario, then the solution is constant and linear, respectively. But consider that if-statement succeeds have the time, what will be the complexity of the nested loop?

What I tried so far is that it will be 2 + (n/2)(2 + 1) + (n/2)(2 + 3) = 2 + 4n

in which 2 is the initialization and comparison, and (n/2)(2 + 1) is when the if-statement succeeds, and (n/2)(2 + 3) is for the else-statement.

But I think it is entirely wrong. What I think I'm missing is that the break statement simply ends the loop, and everything becomes confusing. should it just be n/2

What you maybe could do is finding out the probability of your algorithm to actually go into your if and else statement. Then you can average the complexities by summing them up weighed by their chance of being executed. What you then have is the average complexity (obviously not to be confused with the worst case complexity).

Average = p * O(IF-STATEMENT) + (1 - p) * O(ELSE-STATEMENT) where p is the probability that the if-statement is executed, 0 => p >= 1.

EDIT: Witn probability here I don't imply randomness, you could see it as a way of defining the ratio between calls on your if and else statement, and you might be able to derive that ratio from the predicate in your if-statement.

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