简体   繁体   中英

Best and Worst case Complexity

Please help me finding the complexity of following code:

public static int method(int[] array, int n) {
     for (i = 1; i < n; i++)
         for (j = 1; j <= i; j++)
            if (array[j] < array[j+1])
               for (k = 1; k <= n; k++)
                    array[k] = array[k] * 2;
}

I need to know how BIG-O is calculated in best and worst case taking this code as an example

Best case is O(n^2) worst case is O(n^3).

The outer 2 loops execute no matter what.

The first loop runs i = 1 to n. It executes n times.

The second loop runs up j = 1 to i . It executes n * (n - 1) / 2 times, which makes it

O(n^2).

The third loop is behind an if sentence. So in best case scenario, it never executes and in worst case scenario it always executes. The third loop executes n times for each execution of second loop.

So O(n^3) is worst case (if evaluates to true every time).

Let's say n is 11;

First loop executes 10 times.

Second loop executes (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) times which is 10 * 9 / 2 = 45 times.

This is 1/2 * 10^2 - 5 -> O(n^2) since the quadratic function is the biggest.

In case if always evaluates to true, the innermost loop executes:

45 & 10 times = 450 = 1/2 * 10^3 - 50 -> O(n^3), cubic factor being the largest.

For this kind of questions, the best thing you can do is drawing a table.
Let n be some number, and because of worst-case scenario, lets assume that the if is always satisfied:

  i  |  j  |  k
-----+-----+-----
  1  |  1  |  1
  1  |  1  |  2
  1  |  1  | ...
  1  |  1  |  n
  2  |  1  |  1
  2  |  1  |  2 
  2  |  1  | ...
  2  |  2  |  n
  2  |  2  |  1
  2  |  2  |  2
  2  |  2  | ...
  2  |  2  |  n
 ..  | ..  |  ..

If you continue doing this, you'll get an intuition about "how many times the inner loop executes depending on n ", and you'll get that it's O(n 3 ) - I highly recommend you to fill the table with more values in order to better understand what complexity is.

For the best scenario, you'll assume the opposite ( if is never satisfied) so you'll get a simple nested loop, which will be O(n 2 ).

O(n^2) best-case: for a reverse-sorted array; and

O(n^3) worst-case: for a sorted array.

A couple of additional notes:

Arrays in java are zero-indexed. It's generally bad practice to initialize your counters to 1, you should initialize them to 0; otherwise you risk unintentionally skipping array[0] .

If ever array.length == n , you will get 2 ArrayIndexOutOfBoundsException s:

(1st) In array[j+1] when j==i==n-1

(2nd) In array[k] when k==n .

You'll get another ArrayIndexOutOfBoundsException if ever array.length < n in array[j] .

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