Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run time of nested loops

Sorry if this question has already been asked, I wasn't sure how to search for it.

Say you have the following loop

    for (i=0; i < n; i++)
         for(j = i; j < n; j++)

Would this be O(n^2) or O(nlog(n)) and why?

like image 409
segfault Avatar asked Oct 19 '14 00:10

segfault


1 Answers

The outer loop's runtime (by itself) is O(n), and the inner loop's runtime is O(n-i). So the loop's time would be (n)(n-i), and when you throw away the constant i, the runtime would be O(n^2).

like image 77
Tetramputechture Avatar answered Nov 03 '22 00:11

Tetramputechture