Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of algorithm

What is the complexity given for the following problem is O(n). Shouldn't it be O(n^2)? That is because the outer loop is O(n) and inner is also O(n), therefore n*n = O(n^2)?

The answer sheet of this question states that the answer is O(n). How is that possible?

public static void q1d(int n) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        count++;
        for (int j = 0; j < n; j++) {
            count++;
        }
    }
}

The complexity for the following problem is O(n^2), how can you obtain that? Can someone please elaborate?

public static void q1E(int n) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        count++;
        for (int j = 0; j < n/2; j++) {
            count++;
        }
    }
}

Thanks

like image 640
Harminder Avatar asked Jan 17 '12 05:01

Harminder


Video Answer


1 Answers

The first example is O(n^2), so it seems they've made a mistake. To calculate (informally) the second example, we can do n * (n/2) = (n^2)/2 = O(n^2). If this doesn't make sense, you need to go and brush up what the meaning of something being O(n^k) is.

like image 167
Yuushi Avatar answered Oct 05 '22 02:10

Yuushi