'Determine the big O running time
I am struggling with this question would like some help , thank you.
Determine the big O running time of the method myMethod() by counting the approximate number of operations it performs. Show all details of your answer. Note: the symbol % represent a modulus operator, that is, the remainder of a number divided by another number.
𝑠𝑡𝑎𝑡𝑖𝑐 𝑖𝑛𝑡 𝑚𝑦𝑀𝑒𝑡ℎ𝑜𝑑(𝐴[], 𝑛) {
𝑐𝑜𝑢𝑛𝑡 ← 0
𝑓𝑜𝑟 𝑖 ← 0 𝑡𝑜 𝑛 − 1 {
𝑓𝑜𝑟 𝑗 ← 𝑖 𝑡𝑜 𝑛 − 1 {
𝑐𝑜𝑢𝑛𝑡 ← 𝑐𝑜𝑢𝑛𝑡+ 𝐴[𝑗]
𝑘 ← 1
𝑤ℎ𝑖𝑙𝑒 (𝑘 < 𝑛 + 2) {
𝑖𝑓 (𝑗%2 == 0) {
𝑐𝑜𝑢𝑛𝑡 = 𝑐𝑜𝑢𝑛𝑡 + 1
}
𝑘 + +
}
}
}
𝑟𝑒𝑡𝑢𝑟𝑛 𝑐𝑜𝑢𝑛𝑡
}
Solution 1:[1]
The outer for loop with the variable i runs n times.
The inner for loop with the variable j runs n - i times for each iteration of the outer loop. This would make the inner loop run n + n-1 + n-2 +...+ 1 times in aggregation which is the equivalent of n * (n+1) / 2.
The while loop inside the inner for loop runs n + 1 times for each iteration of the inner for loop.
This makes the while loop to run (n * (n+1) / 2) * (n + 2). This produces (n^2 + n) / 2 * (n + 2) = (n^2 + n) * (n + 2) / 2 = (n^3 + 2n^2 + n^2 + 2n) / 2 = (n^3 + 3n^2 + 2n) / 2).
Dropping lower degrees of n and constants we get O(n^3).
You could have also argued that n + n-1 + ... + 1 is O(n^2) times a linear operation becomes O(n^3). Which would have been more intuitive and faster.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
