简体   繁体   中英

what is the time complexity of the following loop

for (int i=0; i<N; i++)
 for (int j=i; j<N; j++)
  fun1(i,j);

Above is a nested for loop. The first for loop goes from 0 to N, and the second for loop goes from i to N. What is the time complexity of the above code?

edit: fun1 is o(1)

O(n²*O(fun)). Clearly the answer depends on the complexity of fun.

Edit: As fun() = O(1), the complexity loop complexity is O(n²)

The number of loops are as follows 1+2+3+...+N which is N * (N + 1)/2 = N^2/2 + N/2. So, the time complexity is O(N^2/2 + N/2) = O(N^2)

由于fun1()是恒定时间,因此循环的复杂度为O(N^2)

The outside for loop will run the inner for loop N times.

The inner for loop will call the fun1(i,j) N times on the first cycle of the outer loop. Then (N-1) times on the second cycle of the outer for loop. Then (N-2) times, then (N-3) times and so on all the way to the N-th cycle (i = N-1) of the outside loop when fun1(i,j) will run only once. So we are running fun1(i,j) an average of N/2 times on every iteration of the inside loop.

Thus assuming fun1(i,j) has a complexity of O(fun1(i,j)) we get a total complexity of O(n * (n/2) * O(fun1(i,j))) = O(n^2/2 * O(fun1(i,j))) But since we can ignore numerical constants for large values of N to gauge complexity the order of complexity of your code will be O(n^2 * O(fun1(i,j)))

Since fun1(i,j) is constant time O(fun1(i,j)) = O(1) and the complexity of your code will be O(n^2)

A similar example can he seen here in this Selection Sort Algo . See the selection sort algorithm. Here instead of your fun1(i,j) a simple assignment line 'index_of_min = y;' is used but this is just like your example and may be helpful.

The body of the inner loop executes N + (N - 1) + (N - 2) + ... + 3 + 2 + 1 times

and N + (N - 1) + (N - 2) + ... + 3 + 2 + 1 <= N * N therefore the body of the loop will run number of times which has a growth O(n^2)

The total growth of time of the code will depend on the complexity of fun1 () . If fun1 () has a growth of time O(fun1) then fun1 () being executed O(N^2) times the answer will be: O(n^2 * O (fun1 ()))

EDIT

As you have edited that fun1 () is O(1) so the total complexity is O(n^2 * O (fun1 ())) = O(n^2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM