What is the worst case time complexity for this algorithm?

筅森魡賤 提交于 2019-12-02 02:52:12

问题


procedure matrixvector(n:integer);
var i,j:integer;
begin
  for i<-1 to n do begin
    B[i] = 0;
    C[i] = 0;
    for j<-1 to i do 
      B[i]<- B[i]+ A[i,j];
    for j<-n down to i+1 do
      C[i]<-C[i] + A[i,j]
  end
end;

回答1:


O(n^2), if I read it right.

Why you need two inner loops is beyond me. Why not sum B and C in the same loop?




回答2:


worst case is O(n²).

there are indeed three loops, but not all inside each other, thus giving O(n²).

also, you can clearly see that the inner loops won't go from 1 to n (like the outer loop does). But because this would only change the time complexity by some constant, we can ignore this and say that it is just O(n^2).

This shows that time complexity is a measure saying: your algorithm will scale with this order, and it won't ever take any longer. (faster is however always possible)

for more information about "calculating" the worst case complexity of any algorithm, I can point you to a related question I asked earlier




回答3:


Just explaining in detail for beginners:

Outermost for loop will run n times (0 to n) Then there are two for loops within the out ermost for loop. First for loop will go from 1 to n (1+2+3+4+.....+n) And the second for loop will go from n to 1 (n+n-1+n-2+....+1)

The summation formula for (1+2+3+4+5+....+n ) is n(n+1)/2

so the total running time can be computed as n + n(n+1)/2 + n(n+1)/2

Observe the highest polynomial in this equation, it is n^2.

We can further simplify this equation and drop the constants and ignore the linear part, which will give us a run time of n^2.



来源:https://stackoverflow.com/questions/428068/what-is-the-worst-case-time-complexity-for-this-algorithm

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