Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this algorithm O(N)?

Tags:

c

algorithm

big-o

The following C code is apparently O(N) (according to my practice exam). However, I am not sure as to why it is O(N) and not O(Something*Something).

void doit(int N) {
    while (N) {
        for (int j = 0; j < N; j += 1) {
        }
        N = N / 2;  
    }
}

Anyone care to give me some insight to this problem?

Thanks in advance!

like image 937
user2109258 Avatar asked Dec 01 '22 00:12

user2109258


1 Answers

Because N + N/2 + N/4 + ... = 2N.

like image 111
Paul Hankin Avatar answered Dec 05 '22 05:12

Paul Hankin