






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







1
2
3
4
int n = 1000; long sum = 0; for(int k = 1; k <= n; k++) sum += k;
500? 2 ms
2000? 5 ms 10,000? 21 ms
7
int n = 127; for(int k = 1; k <= 500; k++) System.out.print(k * n);
8
int n = 127; for(int k = 1; k <= 500; k++) System.out.print(k * n);
The "change" in T is constant, i.e., T does not depend on the size of n.
9
int n = 127; for(int k = 1; k <= 500; k++) System.out.print(k * n);
10
int n = 100; int table[][] = new int[n][n]; for(int row = 0; row < n; row++) for(int col = 0; col < n; col++) table[row][col] = (row+1) * (col+1); Suppose that this code executes in 10 ms. What is the expected execution time if n is changed to 200? 1000? 50?
13
14
Draw a triangle: int n = 40; for (int row = 1; row <= n; row++){ for (int col = 1; col <= row; col++) System.out.print(''); System.out.println(""); }* How many times is System.out.print('*'); executed? 1 + 2 + 3 + … + 40 = 820 = n(n+1)/2 = ½(n 2 + n) How does T change when n is doubled to 80? 1 + 2 + 3 + … + 80 = 3240 = approximately 4 x 820 (3280) What is the order of this algorithm? Drop the constant, and use the dominating term This algorithm is O (n^2 ) … not O (n^2 + n)
15
How many times is System.out.println(n); executed?
This algorithm is O (log 2 n) = O (log n)
Find out how many times an integer can be divided by 2: int n = 1000; while (n > 0){ System.out.println(n); n /= 2; }
16
Note:
When we say O (log n) the base of the logarithm isn’t important. Why?
Because, e.g., (log 2 n) = log (^) x n / (log (^) x 2). (log (^) x 2) is a constant which can be dropped.
19
2,000,
10,000,000,000 (perhaps as many as 1 trillion)
20
4096 log 4096 x 1024 log 1024 3
=
21