-1

I am looking for the time complexity of the following nested loops, where the inner loop is shrinking.

function(int n){
  c=0;
  for(int i=1;i<=n;i++)
    for(int j=i;j<=n;j++)
      c++;
}
Raphael
  • 72,336
  • 29
  • 179
  • 389
Rizwan Ahmed
  • 11
  • 1
  • 2

1 Answers1

3

It's not hard to see how many times c gets incremented. Each $+$ in the table below represents one c++ operation.

$$\begin{array}{r|ccccccc} &i=1&2&3&4&5&6&\cdots&n \\ \hline \\ j=1& +&+&+&+&+&+&\cdots&+& \\ 2& &+&+&+&+&+&\cdots&+& \\ 3& & &+&+&+&+&\cdots&+& \\ 4& & & &+&+&+&\cdots&+& \\ 5& & & & &+&+&\cdots&+& \\ 6& & & & & &+&\cdots&+& \\ \vdots& & & & & & &\ddots&+& \\ n& & & & & & & &+& \\ \end{array}$$

The total number of $+$ operations is

$$\begin{align} 1 + 2 + 3 + \cdots + n =&\ \frac{n (n + 1)}{2} \\ =&\ \frac{n^2}{2} + \frac{n}{2} \end{align}$$

… which is roughly $\dfrac{n^2}{2}$, which is usually just characterized as $O(n^2)$. You can also see that roughly half of the $n \times n$ square is filled in.

200_success
  • 1,012
  • 7
  • 12