Merge sort running time

回眸只為那壹抹淺笑 提交于 2019-12-07 13:11:14

问题


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)?


回答1:


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 least n 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)).




回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!