Algorithm Analysis
Algorithm Analysis
Consider the following algorithm for computing prefix averages. The i-th prefix average of a vector X
is the average of the first (i + 1) elements of X. A(i) = (X (0) + X (1) + · · ·+ X(i))/ (i+ 1)
function A = prefixaverages(X)
<-1-> A = X;
<-1-> n = length(X);
<-(n)-> for i = 1: n
<-(n)-> s = X (1);
<-n*(n-1)-> s = s + X(j+1);
end
end
end
a) Determine the number of instructions executed and the time complexity of this algorithm.
= 2 + 3n + n^2 – n + n^2 – n
= 2n2 + n + 2
Hence the number of iterations will be 2n2+ 2n + 2 and the time complexity will be O(n^2)