Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 2 ANALYSIS OF ALGORITHMS Part 2. 2 Running time of Basic operations Basic operations do not depend on the size of input, their running time is.

Similar presentations


Presentation on theme: "CHAPTER 2 ANALYSIS OF ALGORITHMS Part 2. 2 Running time of Basic operations Basic operations do not depend on the size of input, their running time is."— Presentation transcript:

1 CHAPTER 2 ANALYSIS OF ALGORITHMS Part 2

2 2 Running time of Basic operations Basic operations do not depend on the size of input, their running time is O(1) Example: The time to compare 2 numbers does not depend on how many numbers we have to compare.

3 3 Counting the number of operations – FOR loops The running time of a for loop is at most the running time of the statements inside the loop times the number of iterations.

4 4 Example sum = 0; for( i = 0; i < n; i++ ) sum = sum + i; The running time is O(n)

5 5 Counting the number of operations – nested loops The total running time is the running time of the inside statements times the product of the sizes of all the loops

6 6 Example sum = 0; for( i = 0; i < n; i++) for( j = 0; j < n; j++) sum++; The running time is O(n 2 )

7 7 Counting the number of operations Consecutive program fragments Total running time : the maximum of the running time of the individual fragments

8 8 Example sum = 0; O(n) for( i = 0; i < n; i++ ) sum = sum + i; sum = 0; O(n 2 ) for( i = 0; i < n; i++) for( j = 0; j < n; j++) sum++; Total running time: O(n 2 )

9 9 Counting the number of operations If statement if C S1; else S2; The running time is the maximum of the running times of S1 and S2.

10 10 Example If (a < b) a = b; // O(1) else { for (k = 0; k < n; k++) // O(n) array[k] = array[k] + b; } Total running time O(n)


Download ppt "CHAPTER 2 ANALYSIS OF ALGORITHMS Part 2. 2 Running time of Basic operations Basic operations do not depend on the size of input, their running time is."

Similar presentations


Ads by Google