Often when I'm doing an operation comparing an array to itself, I write code along these lines:
function operation (array) {
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
// do something with array, i, and j
}
}
}
While the runtime of this code (starting j
at i + 1
) is clearly faster than a normal double-nested loop, I'm struggling to figure out if that's just a matter of a smaller coefficient or if it should be represented by a different big O.
Is there a better big O for the above function than n squared?
array.length
might have a worst-case step complexity of Θ(#elements) pointer dereferences, for example. So, if we are counting pointer dereferences, and are in such a machine model, then the whole thing is at least O(n³). – Jörg W Mittag Aug 07 '20 at 21:01