Presentation is loading. Please wait.

Presentation is loading. Please wait.

Running Time Exercises

Similar presentations


Presentation on theme: "Running Time Exercises"— Presentation transcript:

1 Running Time Exercises

2 k=1; for (i = 1; i < n; i++) k++;

3 if (x < 3) { k++; } else { k = 1; for (i = 1; i < n; i++) }

4 k = 1; for (i = 1; i < n; i++) for (j = 1; j < m; j++) k++;

5 for (i = 1; i < n * n; i++) k++;

6 k = 1; for (i = 1; i < n; i++) for (j = i + 1; j < n; j++) k++;

7 i = 0; while (i < n * n *n) i = i + (2 * n);

8 i = 1; while (i < n * n) i = i + (n / 4);

9 for (i = 1; i < n; i = 3 * i) { j = 1; while (j < n) j = j + 1; }

10 for (i = 1; i < n; i++) { j = 1; while (j < 10000) j = j + 1; }

11 int. arr = new int[n]; int. i,
int *arr = new int[n]; int *i,*j; for (i = arr; i < arr+n; i++) { j = i; while (j != arr) { *j = *i; j--; }

12 Compare Which one should be chosen? When? for (i = 0; i < n; i++) {
j = 0; while (j < 10000) j = j + 1; } for (i = 0; i < n; i++) { j = 0; while (j < n) j = j + 1; } Which one should be chosen? When?

13 Compare for (i = 0; i < n; i++) { j = 0; while (j < 10000)
j = j + 1; } for (i = 0; i < n; i++) { j = 0; while (j < n) j = j + 1; } n T1(n) - Θ(n) T2(n) - Θ(n^2) 1 ~ 10^4 ~ 1 10^2 ~ 10^6 ~ 100*100=10^4 10^4 ~ 10^8 ~ 10^4*10^4=10^8 10^6 ~ 10^10 ~ 10^6*10^6=10^12 10^8 ~ 10^12 ~ 10^8*10^8=10^16

14 CS202 - Fundamentals of Computer Science II
More Problems 5/11/2019 CS202 - Fundamentals of Computer Science II

15 Recursive Algorithms

16 Factorial int factorial (int n) { if (n == 0) return 1;
return n * factorial(n-1); } T(0) = Θ(1) T(n) = T(n-1) + Θ(1)

17 Hanoi T(0) = Θ(1) T(n) = 2 T(n-1) + Θ(1)
void hanoi (int n, char source, char dest, char spare) { if (n > 0) { hanoi(n-1, source, spare, dest); hanoi(n-1, spare, dest, source); } T(0) = Θ(1) T(n) = 2 T(n-1) + Θ(1)

18 Binary Search Best Case ? T(1) = Θ(1) T(n) = T(n/2) + Θ(1)
int binarySearch (int A[], int x, int low, int high) { if (low > high) return -1; int mid = (low + high) / 2; if (A[mid] == x) { return mid; if (A[mid] > x) return binarySearch(A, x, low, mid-1); return binarySearch(A, x, mid+1, high); } Best Case ? T(1) = Θ(1) T(n) = T(n/2) + Θ(1)

19 Foo T(1) = Θ(1) T(n) = 2T(n/2) + Θ(1) void foo (int n) {
if (n > 1) { foo(n/2); } T(1) = Θ(1) T(n) = 2T(n/2) + Θ(1)

20 Merge Sort T(1) = Θ(1) T(n) = 2T(n/2) + Θ(n)


Download ppt "Running Time Exercises"

Similar presentations


Ads by Google