I've seen in many places that the time complexity of merging 2 n-sized sorted arrays is O(n). Isn't Θ(n) more accurate here?
Thanks in advance!
I've seen in many places that the time complexity of merging 2 n-sized sorted arrays is O(n). Isn't Θ(n) more accurate here?
Thanks in advance!
Proving Θ(f(x)) is more difficult than proving O(f(x)) so many people don't bother. However, in this case it is actually correct that in-place merging two n-sized sorted lists is O(n) for all possible inputs and not Θ(n).
Obviously, copy-merging two n-sized lists can't be better than O(n), because 2*n elements are being copied. However, in-place merging can be implemented in Ω(1) for best case scenarios. This is a simple case when all elements of the first list are smaller or equal to elements in the second list. A merging algorithm can detect this situation in O(1) and do nothing if the elements are already in the correct order, hence Ω(1) for best case.
Conclusion: in-place merging is not Θ(n), but is Ω(1) instead. Actually, in-place merging with additional memory can be Ω(1) and O(n), but without additional memory it takes O(n log n) to merge two n-sized lists, so obviously the question is not about this case.
That's why it is simpler just to say O(n) and not be bothered with the details of in-place vs. copy merging. Also, usually what bothers programmers are the worst case, and the average case, not the best case.
In many cases when people say O(f(n)) they mean Θ(f(n)) worst-case complexity. In-place merging is also Θ(n) for the worst case, just like copy-merging.
People usually refer to all possible runs when they talk about complexity. If worst case is Θ(f(x)) and best case is Θ(g(x)), then it is technically correct to write that O(f(x)) and Ω(g(x)) are tight for all possible cases.
Similarly, if copying an array is Θ(n), there is no sense saying that it is O(2n). That would be technically correct, but a very uncommon use of the big O notation.