Week 07 - Algorithm Efficiency

Week 07 - Algorithm Efficiency - for (int j=i; j<N; j++)...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
for (int i=0; i<N; i++) int t = 0; for (int j=0; j<N; j++) c[i][j] = a[i][j] + b[i][j]; t+=c[i][j]; { } cout << t << endl; { } On each iteration of the inner loop we do a comparison (j<N), an increment (j++), several array accesses, and another increment (t+=). Let's say "C" is the amount of time it takes to do all these steps once. We go through the loop N times, so the time to do the whole inner loop is C*N (it's proportional to N). The outer loop has fewer things going on, and the outer loop is only finished once the inner loop finishes, so a single iteration of the outer loop takes C*N. The outer loop is run N times, so the total running time of the outer loop is C*N^2, which is the running time of the entire algorithm. This is the same N^2 that we saw intuitively. Now let's consider an upper triangular matrix (everything below the main diagonal is always 0) for (int i=0; i<N; i++) int t = 0;
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: for (int j=i; j<N; j++) // key difference c[i][j] = a[i][j] + b[i][j]; t+=c[i][j]; { } cout << t << endl; { } The inner loop executes "N-i" times now instead of N times, so the time it takes will be C*(N-i) Each execution of the loop takes less time as "i"increases. The math is roughly: We ignore constants of proportionality, so essentially this is still N^2 How to calculate growth patterns: Suppose we have 2 NxN matricies (same size) A and B, and want to sum them into a new NxN matrix C. We need to do N^2 additions, and we can see this very easily. However, let's come up with that N^2 number using a generalized technique. As we go we'll also calculate the sum of each row of the resultant matrix and display it. CS Page 1...
View Full Document

This note was uploaded on 04/02/2012 for the course COMPUTER S 32 taught by Professor Smallberg during the Winter '12 term at UCLA.

Ask a homework question - tutors are online