Run time of nested loops

2019-07-13 10:51发布

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?

2条回答
Rolldiameter
2楼-- · 2019-07-13 11:39

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).

查看更多
beautiful°
3楼-- · 2019-07-13 11:47

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

查看更多
登录 后发表回答