SwissMan
SwissMan

Reputation: 5

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: 𝐹(𝑁)

Upvotes: 0

Views: 225

Answers (3)

Foad S. Farimani
Foad S. Farimani

Reputation: 14008

As far as the optimization is concerned you should consider that Scilab (and its fellow mathematical programming languages MATLAB and Octave) are intrinsically vectorized. It means if you are using too many for loops, you should probably go back and read some documentation and tutorials. The canonical version of the code you wrote can be implemented as:

A = [-1, 0, 1, 2, 3, 5, 6, 8, 10, 13, 19, 23, 45];
B = [0, 1, 3, 6, 7, 8, 9, 12, 45];

C = setdiff(A, B);
disp(C);

m = 10;
R = C(C > m);
disp(R);

Result:

-1. 2. 5. 10. 13. 19. 23.

    1. 23.

Upvotes: 0

Serge Steer
Serge Steer

Reputation: 446

"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

Upvotes: 1

8bithero
8bithero

Reputation: 1609

This seems like it's probably homework ;p

As for time complexity, it looks more like it would be O(n²) since you have a for loop, inside another for loop. I recently started watching this course about Algorithms and data structures on Udemy that I highly recommend. He explains BigO notation quite well :) Link to course. (No affiliations to the author)

Upvotes: 0

Related Questions