简体   繁体   English

合并k个排序的arrays的时间复杂度

[英]Time complexity of merging k sorted arrays

I have k sorted arrays, each length n and I want to sort them so there is one sorted array of length n*k.我有k个排序的arrays,每个长度为n,我想对它们进行排序,所以有一个长度为n * k的排序数组。 I know I can iteratively apply merge function from Merge Sort.我知道我可以从合并排序迭代地应用合并 function。 However I don't understand why following code is O(nk^2) instead O(nk).但是我不明白为什么下面的代码是 O(nk^2) 而不是 O(nk)。 I iterate over k array once and each merge subroutine has linear time with respect to its input.我迭代 k 数组一次,每个合并子例程都具有与其输入相关的线性时间。 Where am I wrong?我哪里错了? How to better understand running time of this algorithm?如何更好地理解该算法的运行时间?

def myMerge(left, right):
    l, r = 0, 0
    result = []
    for i in left+right:
        if left[l] <= right[r]:
            result.append(left[l])
            l += 1
            if l >= len(left):
                return result + right[r:]
        else:
            result.append(right[r])
            r += 1
            if r >= len(right):
                return result + left[l:]
    return result

#input
k = [[1,5,8],[2,7,9],[1,1,4]]

result = k[0]
for l in range(1,len(k)):
    result = myMerge(result,k[l])  

Both of your sentences are correct:你的两个句子都是正确的:

  • you iterate over k array once你迭代 k 数组一次
  • each merge subroutine has linear time with respect to its input每个合并子例程相对于其输入具有线性时间

However, the answer is O(nk^2).然而,答案是 O(nk^2)。 Why?为什么?

Because the length of the aforementioned input is not O(n).因为上述输入的长度不是 O(n)。 After the first loop it's already 2*n.在第一个循环之后它已经是 2*n。 After the second, it's already 3*n.在第二个之后,它已经是 3*n。 And so on.等等。 So during the last iteration your array lengths are n*(k-1) and n which means each merge subroutine is O(nk) and therefore the entire algorithm is O(n*k^2)因此,在最后一次迭代期间,您的数组长度为 n*(k-1) 和 n,这意味着每个合并子例程为 O(nk),因此整个算法为 O(n*k^2)

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

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