简体   繁体   中英

How to find runtime of algorithm in big-o

public void do() {
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            // do something

    for (int i = 1; i < rows - 1; i += 2)
        for (int j = 1; j < columns - 1; j += 2) {
            // do something

    for (int i =  50; i > 0; i--)
        // do something

    for (int i = 1; i < rows - 1; i++)
        for (int j = 1; j < columns - 1; j++)
            // do something
}

In this case rows and column would equal:

rows = (size * 10) + 1;
columns = rows + 10;

where size (n) is 1, 2, 4, or 8.

Since the rows and columns variables will increase with respect to the size and each loop will run over the rows and then the columns inside the loop can I say that this function would run in O(n^2) ?

I am fairly new with the whole complexity of an algorithm would love some input on this. Thank so much.

Directly answering your code : What is the Big-O of a nested loop, where number of iterations in the inner loop is determined by the current iteration of the outer loop?

N is for one loop, so two nested = N^2, etc. If there is 2 instructions in the nested loop, it would be in reality 2N^2, but the multiplication by two is uselses, so N^2 anyway.

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