简体   繁体   中英

Worst-case running time Big O

Could you please explain how I can get the worst-case Big O of this algorithm. I was reading my textbook and I came across a similar algorithm like this one but still don't understand the logic behind it.

int t=0;
for(int x=0;x<num.length;x++){
    for(int y=0;y<num.length;y++){
        for(int p=0;p<num.length;p++){
            for(int w=0;w<num.length;w++){
                if(num[p][w]>num[x][y])
                {
                    t=num[x][y];
                    num[x][y]=num[p][w];
                    num[p][w]=t;
                }
            }
        }
    }
} 

The logic is pretty simple. Let's start with the most inner loop:

This loop runs num.length times. Its worst case runtime complexity in big-O notation is O(n) assuming n = num.length .

for(int w=0;w<num.length;w++){
    ...
}

Now when you put another for-loop around it of length p , it will run the above for-loop p times. So it is O(pn) . In your case, p = num.length = n so it should be O(n*n) = O(n^2) .

There are 4 nested loops in your example so the answer is O(n^4) .

Why did I ignore the content of the most inner loop? Because there are a constant number of operations done, let that number be c . Asymptotic analysis used by the big-O notation says the following: O(c) is equivalent to O(1) . That comes from the definition of big-O .

If you are comparing an element for; == or < or > against a list or an array of size n, Then its worst case is O(n).

Therefore the cost of one for loop is: O(n), but you have 4 for loops each with a worst case O(n).

Total cost is: n*n*n*n = Worst Case O(n^4).

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