Week 3 Flashcards

1
Q

What is the complexity of the following function?

int temp = 0;
for (i = 0; i < n; i++) {
	for (j = n; j > i; j--) {
		temp = temp + i + j;
	}
}
A

O(n^2)

Always worst case.
In this code snippet, we have two nested for loops, each of which execute a number of times that is dependent on n.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Determine the most appropriate run-time for the following algorithm. Write out your answer in expression form (just include the expression within the “O()” notation in your response).

for (int i = 0; i < n; i++) {
    // do something O(1)
}
for (int j = m; j > 0; j--) {
    for (int k=0; k < n; k++) {
        if (k > j) {
            //do something O(1)
        }
    }
}
A

O(m*n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Determine the most appropriate run-time for the following algorithm. Write out your answer in expression form (just include the expression within the “O()” notation in your response).

for (int i = 0; i < n*n; i = i+10) {
    // do something O(1)
}
A

n^2

+10 like (1/10) faktor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Determine the most appropriate run-time for the following algorithm. Write out your answer in expression form (just include the expression within the “O()” notation in your response).

public int method(int n) {
if (n==0) return 1;
return n * method(n-1);
}

A

O(n)

There is one recursive call in this method. The method decrements by 1 in each call to itself until it reaches 0. The method itself performs constant time operations (e.g. decrementing by 1, returning 1).

The method will run n times performing O(1)operations within the method (outside of the recursive call), so the overall run-time evaluates to O(n).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly