You are on page 1of 3

CS 201 Runtime Analysis

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;
}
}

for (int i = 0; i < 20; i++) {


System.out.println("foo");
}

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

// assume that a[] is an array of integers


int n = a.length;
int sum = 0;
int i = 0;
while ((i < n) && (a[i] > 0)) {
sum += a[i];
i++;
}

// assume that a[] is an array of integers


int n = a.length;
int sum = 0;
int i = 0;
while ((i < n) && (i < 10)) {
sum += a[i];
i++;
}

What is the worst-case time complexity of:

1. searching for an element in an unsorted list?

2. finding the smallest element in an unsorted list?

3. finding the smallest element in a sorted list?

You might also like