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++;
}
Computer Science Stack Exchange is a question and answer site for students, researchers and practitioners of computer science. It only takes a minute to sign up.
Sign up to join this communityI 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++;
}
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.
c
.
$\endgroup$