I am very much confuse that why complexity of this program is O(n)?
int j = 0;
int i;
For (i = 0; i < n, i++) // O(n)
{
For (i = 0; i < n, i++)//O(n)
{
While (j < n)// O(n)
{
Statement; j++;
}
}
}
I am totally new to Algorithms. Any help and explanation will be appreciated.
j++
invoked? – fade2black Jan 03 '18 at 18:49Statement; j++
is executed $n$ times for only $i=0$ and never executed for $i>0$. The outer for-loop runs only once for $i=0$. You could observe it by running this code. – fade2black Jan 03 '18 at 19:00Statement; j++
is invoked $n$ times (total!), and the second for-loop increments $i$ $n$ times (total!), and the outer for-loop increments $i$ only once after which it quits since $i$ reaches $n$ (by the second for-loop). This gives $n+n +1= 2n+1$ which is $O(n)$. – fade2black Jan 03 '18 at 19:08