I know that the running time of merge sort is O(n*lg(n)) and that merge sort is a comparision sort, which also means that it takes Ω(n logn) in the worst case to sort a list.
Can I therefore conclude that the running time of merge sort is theta(n*lg n)?
If something is O(X)
and Omega(X)
, this implies it is Theta(X)
. And log_b1(...)
is the same as log_b2(...)
times a conversion factor constant.
What you said was (translated):
I know that the running time of merge sort is, in the worst case, no worse than
n log(n)
. [You arrived at this conclusion somehow with math.] But comparison sorts take at leastn log(n)
in the worst case.
Thus it makes sense that the worst-case behavior of merge sort is exactly n log(n)
.
This is of course with the implicit assumption that you have no information about your sequence.
edit: You could also prove it from first principles. The thing to note is that you can merge two sorted arrays in linear Theta(N1+N2) time while keeping them merged (by scanning across them kind of in parallel). (Subdividing the array, nomatter what sequence you get, will always take Theta(log(N)) time, which is small so we just ignore that.) We now note that each element has to be merged Theta(log(N)) times (the depth of the tree, if you draw it out). Thus the Theta(N log(N)).
Yes, the complexity of merge sort is theta(n*lgn). And there is another way you can get sure about that.
The merge sort is known to be a divide-and-conquer algorithm. First it divides the array of size n in two n/2 parts, then recurses on both of them and finally merges the result into a sorted array.
Let's suppose that the merge sort time is T(n). Then:
- the dividing operation is constant theta(1) - you just need to find the middle element of the array by dividing it's length by 2
- the recursion on each part of the array takes T(n/2) time which makes 2T(n/2) for both of them
- the merge operation is known to have theta(n) complexity
So finally you get the following recurrent equation for T(n) = :
theta(1) | if n == 1
2*T(n/2) + theta(n) | if n > 1
Solving this equation you get T(n) = theta(nlgn);
For more details you can refer to "Introduction to algorithms" book by Corman.
来源:https://stackoverflow.com/questions/5926893/merge-sort-running-time