0% found this document useful (0 votes)
4 views1 page

Algorithm Analysis

The document discusses an algorithm for computing prefix averages of a vector. The algorithm uses two for loops to calculate the average of the prefixes. The time complexity of the algorithm is analyzed to be O(n^2) where n is the length of the input vector, as there are two nested loops.

Uploaded by

Phiwokwakhe Pho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Algorithm Analysis

The document discusses an algorithm for computing prefix averages of a vector. The algorithm uses two for loops to calculate the average of the prefixes. The time complexity of the algorithm is analyzed to be O(n^2) where n is the length of the input vector, as there are two nested loops.

Uploaded by

Phiwokwakhe Pho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

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))-> for j = 1: i-1

<-n*(n-1)-> s = s + X(j+1);

end

<-n-> A(i) = s/i;

end

end

a) Determine the number of instructions executed and the time complexity of this algorithm.

Therefore, the time complexity will be

T(n) = 1 + 1 + n + n + (n*(n-1)) + (n*(n-1)) + n

= 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)

b) Implement this algorithm and practically determine its time complexity.

You might also like