Space requirements of a merge-sort

主宰稳场 提交于 2019-11-30 08:26:39

There are versions of merge-sort that can work in place.

However, in most implementations the space is linear in the size of the array. That means n for the first level, n/2 for the second, n/4 for the third, etc. By the time you are at the bottom of your recursion, this series adds up to about 2n, which is linear.

This is my explanation for the space complexity for your code. Basically, as the algorithm reaches results how are we doing on memory.

1) Every recursion call you make has a constant size of stack frame allocated as well as any variables that are not a function of "n". Let's call this constanct "c". Since, you are going lg(n) levels deep the result is c*lg(n) which is O(lg(n)).

2) Now, as we compute the result, we allocate space for n/(2^k) elements, where k is the level you are at.

left = merge_sort(left)
right = merge_sort(right)

For folks who may be wondering how we came up with n/(2^k), notice that first we go about allocating memory when solving the first half of the array i.e left=merge_sort(left). Once, this recursion tree is ended, we end up deallocating all memory and come back to starting point before solving for the right side. Hence, its n/(2^k). This is going to be O(n).

3) Finally, merge procedure may allocate extra space too (if using linked list this space may not be needed) which is O(n)

Final answer = O(lg(n)) + O(n) + O(n) which is O(n).

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