For a pseudocode algorithm like this:
Algorithm fn(A, S):
Inputs: array A of n integers
integer S
for i from 0 up to n - 1:
for j from i + 1 up to n - 1:
for k from j + 1 up to n - 1:
if A[i] + A[j] + A[k] == S:
return true
return false
Why is its worst-case time-complexity O(n^3). I am new to big-O notation and I need a bit of help explaining why this function's worst-case would be O(n^3). I reasoned that it was O(n^3) because it has three for loops; but, I also feel that this is a shallow understanding.
What you have shown is an example of a polynomial-time algorithm. You’re correct that the worst case would be O(n^3) from the THREE nested
forloops.The worst case in this example would be if a match between the values of
A[i] + A[j] + A[k]and theintger Swas not found until the very last possible nested iteration. Contrastingly, the best case would be if the match were found on the first time through.