Home > OS >  Space complexity for mergesort
Space complexity for mergesort

Time:01-18

It is unclear for me if this snippet of merge sort has space complexity of O(n log n) or 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)) (i.e 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) ? A lot of sources on the internet use the exact same implementation and they say that the space complexity is O(n), and I do not understand why?

CodePudding user response:

The space complexity is O(N), which is not just expected case, but also best and worst case. 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. When the memory for the merge is done, it's released - it doesn't remain in use. All merges can (re)use the same chunk of N locations.

CodePudding user response:

The time complexity is O(nlog(n))

  • Related