Professional Documents
Culture Documents
Big O
Big O
Express the worst-case runtime complexity of the following code snippets using big-O nota-
tion, as a function of n.
int sum = 0;
for (int i = 0; i < n; i += 2) {
sum += i;
}
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = n; j > 0; j--) {
sum += j;
}
}
int sum = 0;
for (int i = 0; i < n; i += 2) {
for (int j = 0; j < n; j+= 4) {
sum += (i + j);
}
}
CS 201 Runtime Analysis
int sum = 0;
for (int i = 0; i < n; i += 2) {
sum += i;
}
for (int j = 0; j < n; j += 4) {
sum += j;
}
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
sum += j;
}
}
int prod = 1;
while (prod < n) {
prod *= 2;
}
int sum = 0;
for (int i = 1; i < n; i *= 2) {
for (int j = 0; j < n; j++) {
sum += j;
}
}
CS 201 Runtime Analysis