Practice 3
Practice 3
Practice
Sample to practice
Computing Prefix Averages Algorithm
We further illustrate asymptotic analysis with two
algorithms for prefix averages
The i-th prefix average of an array X is average of
the first (i + 1) elements of X:
A[i] = (X[0] + X[1] + … + X[i])/(i+1)
1. Calculate running time
Algorithm prefixAverages1(X, n)
Input array X of n integers
Output array A of prefix averages of X #operations
A new array of n integers ---------- n
for i 0 to n 1 do ---------- n
{ s X[0] ---------- n
for j 1 to i do ---------- 1+
2 + …+ (n 1)
s s + X[j] ----------
1 + 2 + …+ (n 1)
A[i] s / (i + 1) } ---------- n
return A T(n) =----------
n+n+n+(1+2+…+(n-1)) + (1+2+…+(n-1))
1 + n+1
= 2(1+2+…+n) + 2n + 1 = n(n+1)+2n+1
= n2+3n+1
2. Simplify and return big Oh
Simplify T(n) = n2
Thus, algorithm prefixAverages1 runs in O(n2) time
Practice
Insert additional 2 slides after each algorithm
• Calculate total running time into a function
• Simplify the running-time function and indicate the big Oh
Find maximum number in nxn matrix
0 n-1
Algorithm: 0 6 4 … 2
Input: A, n 12 3 … 9
curMax = A[0][0] … … … …
for i=0; i<n; i=i+1 n-1 5 8 … 1
Algorithm Ex1(A, n)
Input an array X of n integers
Output the sum of the prefix sums A
s0
for i 0 to n 1 do
{ s s + A[0]
for j 1 to i do
s s + A[j]
}
return s
Determine how many elements of array
1 match elements of array 2
Algorithm?
0 n-1
Algorithm:
2 4 … 6
Input: A, B, n
0 n-1
for i=0; i<n; i=i+1 6 8 … 3
for j=0; j<n; j=j+1
if A[i] == A[j]
matches++
break
Maximum subsequence sum (2)
int MaxSubSum2 (int A[], int N)
{
int thissum, maxsum, i, j;
1. maxsum = 0;
2. for (i=0; i<N; i=i+1)
3. {
3. thissum = 0;
4. for (j=i; j < N; j=j+1)
5. {
5. thissum += A[j];
6. if (thissum > maxsum)
7. maxsum = thissum;
}
}
8. return maxsum;
}
Linear Search algorithm