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

為{幸葍}努か 提交于 2019-11-26 21:24:07

问题


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 of using merge sort, which I assume in this case will consume O(log n+m).

I am not really good with big-oh and stuff. Please suggest me the time complexity for this problem and let me know if there is an even optimized way of solving the problem.

Thanks in advance.


回答1:


Attention! This answer contains an error

A more efficient algorithm exists and it is presented in another answer.


The complexity is O(m log n).

Let the long array be called a and the short array be b then the algorithm you described can be written as

  for each x in b
      insert x into a

There are m iterations of the loop. Each insertion into a sorted array is an O(log n) operation. Therefore the overall complexity is O (m log n).

Since b is sorted the above algorithm can be made more efficient

  for q from 1 to m
      if q == 1 then insert b[q] into a
      else 
         insert b[q] into a starting from the position of b[q-1]

Can this give better asymptotic complexity? Not really.

Suppose elements from b are evenly spread along a. Then each insertion will take O(log (n/m)) and the overall complexity will be O(m log(n/m) ). If there exists a constant k>1 that does not depend on n or m such that n > k * m then O(log(n/m)) = O(log(n)) and we get the same asymptotic complexity as above.




回答2:


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.



来源:https://stackoverflow.com/questions/11039217/time-complexity-for-merging-two-sorted-arrays-of-size-n-and-m

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