Optimization, time complexity and flowchart (Scilab)

你离开我真会死。 提交于 2020-03-26 03:22:01

问题


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


回答1:


"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



回答2:


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)




回答3:


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.


来源:https://stackoverflow.com/questions/59653668/optimization-time-complexity-and-flowchart-scilab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!