Time complexity for merging two sorted arrays of size n and m

后端 未结 3 1276
再見小時候
再見小時候 2020-12-06 07:36

I was just wondering what is the time complexty of merging two sorted arrays of size n and m, given that n is always greater than m.

I was thinking

3条回答
  •  时光说笑
    2020-12-06 08:17

    The time to merge two sorted lists is definitely not O(m log n). It is O(n+m).

    The code looks something like this:

    allocate c with length n+m
    i = 1
    j = 1
    while i < n or j < m
      if i = n
        copy rest of b into c 
        break    
      if j = m
        copy rest of a into c
        break
      if a[i] < b[j]
        copy a[i] into c
        i=i+1
        continue
      if b[j] < a[i]
        copy b[j] into c
        j=j+1
        continue
    

    Now if we don't have enough memory to allocate c this can be modified to still be O(n+m) time as most hardware (both RAM and hard disks for instance) allow for block operations. when we need to insert a single item into the middle of the array it is a single operation to move the tail end of the block over one to make room. If you were on hardware that didn't allow this then you'd perhaps have O(n) for each insert, which would then be O(n+mn) complexity. Since we only need to insert elements of the smaller array into the larger we never need to shift pieces of the larger array when the element from that one is already in the right place. Hence, the n stays the same and the complexity of the m-bit is increased. This is worst case shown when all of array b with length m is properly placed in front of array a of length n.

提交回复
热议问题