[英]Time and space complexity of divide and conquer k-way-merge algorithm
Given that A is an array of k arrays. 假设A是k个数组的数组。 Each inner array is sorted and contains m elements. 每个内部数组都已排序并包含m个元素。
Given this algorithm for merging K-sorted arrays held in A: 给定用于合并A中保存的K个排序数组的算法:
// A is array of sorted arrays
K-arrays-merge(A)
1. if A.length == 1
2. return first element of A
3. half = length[A] / 2
4. firstHalfArray = new array[half][m];
5. secondHalfArray = new array[half][m];
6. for (i = 0; i < half; i++)
7. do firstHalfArray[i] = A[i];
8. for (i = half; i < length[A]; i++)
9. do secondHalfArray[i] = A[i];
10. secondHalfArray = Copy second half arrays from A
11. a = K-arrays-merge(firstHalfArray)
12. b = K-arrays-merge(secondHalfArray)
13. return merge(a,b) // This is a merge between two sorted arrays with time complexity of O(n)
Why is the time comelexity of this algorithm is O(m*klogk)? 为什么该算法的时间复杂度为O(m * klogk)?
My first thought is that the recursive method runs logk times, in each round copying the arrays is O(m * k) and the merge-sort is O(mi log (mi)) where 1 <= i <= logk
我的第一个想法是递归方法运行logk次,在每一轮中,数组复制为O(m * k),合并排序为O(mi log(mi)),其中1 <= i <= logk
When looking at the divide and conquer steps: 查看分而治之的步骤:
1 <= i <= logk
. 合并-合并排序,复杂度为O(mi log(mi)),其中1 <= i <= logk
。 I do not know how to calculate the time complexity from this. 我不知道如何从中计算时间复杂度。 Also what would be the space complexity for this algorithm? 另外,该算法的空间复杂度是多少?
If we suupose n = mk
, time complexity would be T(k) = 2T(k/2) + n + n
. 如果我们使n = mk
合适,则时间复杂度将为T(k) = 2T(k/2) + n + n
。 n
for array copy, n
for merging and 2T(k/2)
for recursive call. n
用于数组复制, n
用于合并, 2T(k/2)
用于递归调用。 Hence, time complexity of the algorithm is O(nlog k) = O(mk log(k))
. 因此,算法的时间复杂度为O(nlog k) = O(mk log(k))
。
As each time all values of the array copied and stored in the stack, and the depth of stack is O(log k)
, space complexity would be O(n log k) = O(mk log k)
. 每次数组的所有值都复制并存储在堆栈中,并且堆栈深度为O(log k)
,空间复杂度将为O(n log k) = O(mk log k)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.