Search code examples
optimizationtime-complexityshortcodescilabflowchart

Optimization, time complexity and flowchart (Scilab)


I tried to optimize this code, but it’s impossible to optimize anymore.

Please help with building a flowchart for this algorithm.

A = [-1,0,1,2,3,5,6,8,10,13,19,23,45];
B = [0,1,3,6,7,8,9,12,45];
N1 = length(A);
N2 = length(B);
t = 1;
m = 10;
C = [];
for i=1:N1
    for j=1:N2 
        if A(i)==B(j)
            break
        else
            if j==N2
               C(t)=A(i);
               t=t+1;
           end
       end
   end
end
disp(C);
N3=length(C);
R = [];
y = 1;
for l=1:N3
    if C(l)>m
       R(y)=C(l);
       y=y+1;
   end 
end
disp(R);

How to find time complexity of an algorithm

I think it should be O(n).

Dominant (elementary) operation: comparison A(i)== B(j)
But I am not sure yet.

And I can't do

Complexity function (worst case)

and

Worst Computing Complexity: 𝐹(𝑁)


Solution

  • "Optimization" depends of your goal for exmple you may want to minimize the number of floating point operation or to minimize the number of Scilab instruction or minimize the execution time of the algorithm.

    As Scilab is an intepreted langage it is possible to reduce the execution time ans code length applying vectorization.

    For example your code

    N3=length(C);
    R = [];
    y = 1;
    for l=1:N3
        if C(l)>m
           R(y)=C(l);
           y=y+1;
         end 
    end
    

    may be rewritten:

    R=C(C>m)
    

    Here the number of computer operations is more or less the same as in the original code, but the execution time is many times faster:

    Let C=rand(1,1000);m=0.5;

    --> timer();R=C(C>0.5);timer()
    ans  =
       0.000137
    
    --> timer();
    -->   N3=length(C);
    -->     R = [];
    -->     y = 1;
    -->     for l=1:N3
      >         if C(l)>m
      >            R(y)=C(l);
      >            y=y+1;
      >         end 
      >     end
    
     --> timer()
     ans  =
        0.388749