合并排序空间和时间复杂度

时间:2015-05-11 14:21:05

标签: algorithm

给出以下合并排序算法:

mergesort(A,p,r) 

    if (r <= l) return    //constant amount of time
    int m = (p+r)/2       //constant amount of time

    mergesort(A, p, q)      // these two calls will decide the
    mergesort(A, q+1, r)    // O(logn) factor inside O(n * logn) right?

    merge(A, p, q, r)       lets dwell further


merge(a,p,q,r){

    n1 = q-p+1         //constant time
    n2 = r-q           //constant time

    // Let L[1...n1+1] and R[1...n2+1] be new arrays    // idk , lets say constant

    for i,j in L[],R[]
        L[i] = A[p+i-1]
        R[j] = A[q+j]  // shouldn't this take time varying on size of array?
                       // also extra space too?

    i=1 j =1           // constant time

    for k = p to r     // everything below this will contribute to O(n)
                       // inside O(n*logn) amirite?
        if L[i]<=R[j]
            A[k] = L[i]
            i++

        else A[k] = R[j]
             j++

为什么我们估计它的O(nlogn)时间复杂度,请记住是否创建了要合并的左右数组?

如果使用额外的尺寸,空间复杂度如何变为O(n)?由于填充数组需要n并且O(n)L[]在每个递归步骤中创建,因此不会增加R[]

0 个答案:

没有答案