简体   繁体   中英

What is the time complexity for while loop inside a while loop?

 int i = 0, j = A.size() - 1;
    while (i < j) {
        while ((i < j) && (A[i] % 2 == 0)) ++ i;
        while ((i < j) && (A[j] % 2 == 1)) -- j;
        swap(A[i], A[j]);
        i ++; 
        j --;

We can scan from both ends of the array, swap them if not in place. Why is the time complexity O(N) and not O(N*N)?

You can rewrite the code to make it clearer:

 int i = 0, j = A.size() - 1;
 while (i < j) {
   if (A[i] % 2 == 0) ++ i;
   else if (A[j] % 2 == 1) -- j;
   else {
     swap(A[i], A[j]);
     i++; 
     j--;
   }
 }

The complexity of the algorithm is O(N) because the number of operation will in any case will be ji times only.

Here the inner loops for any iteration of outer loop will execute for ji times.

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