edited by
2,436 views

2 Answers

Best answer
8 votes
8 votes

Outer loop executes $\log{n}$ times ...

For $i=n$, inner loop will execute $n$ times.

For $i=\frac{n}{2}$, inner loop executes $\frac{n}{2}$ times. And so on...


count+=1 statement is in the inner loop, and will be executed $n + \frac{n}{2} + \frac{n}{4} + \ldots + 1$ times.

Solving,

$\underbrace{n + \frac{n}{2} + \frac{n}{4} + \ldots + 1}_{\log{n} \text{ terms}}$

$= n \cdot \frac{1- (1/2)^{\log{n}}}{1/2}$        (using GP, first term $=1$ and common ratio $=1/2$)

$=2n(1-\frac1 n) = 2n - 2$

complexity $=O(n)$

edited by
3 votes
3 votes
The worst case time complexity of this function is O(n)..... the outer loop iterates for O(logn) as the value of n is changing like this.....n,n/2,n/4......1(assuming n is power of 2). Therefore say the ith term will be n/2^(i-1)...now equating this to 1 we get i as O(logn). Hence the number of iterations of the outer loop(the total number of terms in the series) is O(logn). Now for each iteration of the outer loop the inner loop is iterating depending on the value of i i.e for 1st iteration of outer loop inner loop is iterating n times, for 2nd iteration of the outer loop inner loop is iterating n/2 times ..like..this. Therefore the total time complexity becomes ...n+n/2+n/4+.....+1(assuming n power of 2)......therfore, its the sum of g.p series with logn number of terms in it....hence the sum becomes 1.(2^(logn)-1)/(2-1)...which equates to O(n)...

Related questions

2 votes
2 votes
2 answers
2
Vikrant Singh asked Jan 31, 2015
1,732 views
What is the worst case time complexity to find the gcd(m,n) using best algorithm known?A. O(log(min(m,n)))B, O(log(max(m,n)))
0 votes
0 votes
1 answer
3
LavTheRawkstar asked Jan 12, 2017
838 views
INSERTION-SORT (A, n) ⊳ A[1 . . n]for (j ← 2 to len(A) ){key ← A[ j];i ← j – 1 ; while (i 0 and A[i] key) { A[...
1 votes
1 votes
1 answer
4
rahuldb asked May 7, 2017
12,277 views
Derive the best and worst case complexity of insertion sort algorithm?