简体   繁体   English

归并排序的空间复杂度

[英]Space complexity for mergesort

It is unclear for me if this snippet of merge sort has space complexity of O(n log n) or O(n).我不清楚这段合并排序的空间复杂度是 O(n log n) 还是 O(n)。

def mergeSort(L): 
    N = len(L)
    
    if N <= 1:
        return L
    
    mid = N // 2
    L1 = mergeSort(L[: mid])
    L2 = mergeSort(L[mid :])
    return merge(L1, L2)
    

Assuming that merge(L1, L2) uses auxiliar memory of O(len(L)) (ie O(n)), doesn't every level of the recursion tree use O(n) auxiliary memory. And as long the tree has like O(log n) levels wouldn't it be O(n log n)?假设merge(L1, L2)使用O(len(L))的辅助memory(即O(n)),递归树的每一层不都使用O(n)辅助memory。只要树有像 O(log n) 级别不会是 O(n log n) 吗? A lot of sources on the inte.net use the exact same implementation and they say that the space complexity is O(n), and I do not understand why? inte.net 上的很多来源使用完全相同的实现,他们说空间复杂度是 O(n),我不明白为什么?

The time complexity is O(nlog(n))时间复杂度为 O(nlog(n))

The space complexity is O(N) , which is not just expected case, but also best and worst case.空间复杂度为O(N) ,这不仅是预期的情况,也是最好和最坏的情况。 While O(log(N)) levels of recursion may be active, a merge can be in progress only on the current level, and is not itself recursive.虽然O(log(N))级别的递归可能处于活动状态,但合并只能在当前级别上进行,并且本身不是递归的。 When the memory for the merge is done, it's released - it doesn't remain in use.当用于合并的 memory 完成后,它就会被释放——它不会继续使用。 All merges can (re)use the same chunk of N locations.所有合并都可以(重新)使用相同的N个位置块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM