tags:

views:

95

answers:

3

I have question what is complexity of this algorithm

public class smax{

   public static void main(String[]args){

      int b[]=new int[11];
      int a[]=new int[]{4,9,2,6,8,7,5};

      for (int i=0;i<b.length;i++){
         b[i]=0;
      }

      int m=0;
      while (m<b.length) {
         int k=a[0];
         for (int i=0;i<a.length;i++) {
            if (a[i]> k && b[a[i]]!=1) {
               b[a[i]]=1;
            }
         }
         m++;
      }

      for (int i=0;i<a.length;i++){
         if (b[a[i]]!=1){
            b[a[i]]=1;
         }
      }

      for (int j=0;j<b.length;j++){
         if (b[j]==1){
            System.out.println(j);
         }
      }
//result=2 4 5 6 7 8 9
    }
}

?

A: 

Looks like O(b*a)

Midhat
+1  A: 

O(len(b)*len(a))

sza
+1  A: 

Looks like homework so the best answer would not only be the final answer but also one you could learn from.

Let n = a.Lengh, m = b.Length

for (int i=0;i<b.length;i++){
     b[i]=0;
  }

makes one pass on b's elements so it would contribute m steps.

for (int i=0;i<a.length;i++){
     if (b[a[i]]!=1){
        b[a[i]]=1;
     }
  }

makes one pass on a's elements so it would contribute n steps.

for (int j=0;j<b.length;j++){
     if (b[j]==1){
        System.out.println(j);
     }
  }

makes one pass on b's elements so it would contribute m steps.

so far we have 2m+n

int m=0;
  while (m<b.length) {
     int k=a[0];
     for (int i=0;i<a.length;i++) {
        if (a[i]> k && b[a[i]]!=1) {
           b[a[i]]=1;
        }
     }
     m++;
  }

for every element of b there is a pass on all a's elements which contribute mn steps.

the sum of all steps is 2m+n+mn which in the asymptotic notation is O(mn).

Itay