简体   繁体   中英

Complexity of a divide and conquer recursive algorithm

I'm trying to obtain the complexity of a particular divide and conquer algorithm so transpose a given matrix.

From what I've been reading, I got that the recursion should start as follows:

C(1) = 1
C(n) = 4C(n/2) + O(n)

I know how to solve the recursion but I'm not sure if it's right. Everytime the function is called, the problem is divided by 2 (vars fIni and fEnd), and then another 4 functions are called. Also, at the end, swap is called with a complexity of O(n²) so I'm pretty sure I'm not taking that into account in the above recursion.

The code, as follows:

void transposeDyC(int **m,int f,int c, int fIni, int fEnd, int cIni, int cEnd){
    if(fIni < fEnd){
        int fMed = (fIni+fFin)/2;
        int cMed = (cIni+cFin)/2;

        transposeDyC(m,f,c, fIni, fMed, cIni, cMed);
        transposeDyC(m,f,c, fIni, fMed, cMed+1, cEnd);
        transposeDyC(m,f,c, fMed+1, fFin, cIni, cMed);
        transposeDyC(m,f,c, fMed+1, fFin, cMed+1, cEnd);

        swap(m,f,c, fMed+1, cIni, fIni, cMed+1, fEnd-fMed);
    }
}

void swap (int **m,int f, int c,int fIniA, int cIniA, int fIniB, int cIniB, int dimen){
    for (int i=0; i<=dimen-1; i++){
        for (int j=0; j<=dimen-1; j++) {
            int aux = m[fIniA+i][cIniA+j];
            m[fIniA+i][cIniA+j] = m[fIniB+i][cIniB+j];
            m[fIniB+i][cIniB+j] = aux;
        }
    }
}

I'm really stuck in this complexity with recursion and divide and conquer. I don't know how to continue.

You got the recursion wrong. It is 4C(n/2) + O(n 2 ), because when joining the matrix back, for a size n, there are total n 2 elements.


Two ways:

  1. Master Theorem

    Here we have a = 4, b = 2, c = 2, Log b a = 2

    Since, Log b a == c, this falls under the case 2, resulting in the complexity of O(n c Log n) = O(n 2 Log n).


  1. Recurrence tree visualization

    If you'd try to unfold your recurrence, you can see that you are solving the problem of size n by breaking it down into 4 problems of size n/2 and then doing a work of size n 2 (at each level).

    Total work done at each level = 4 * Work (n/2) + n 2

    Total number of levels will be equal to the number of times you'd have to divide the n sized problem until you come to a problem of size 1. That will be simply equal to Log 2 n.

    Therefore, total work = Log(n) (4*(n / 2) + n 2 ), which is O(n 2 Log n).

Each recursive step reduces the number of elements by a factor of 4, so the number of levels of recursion will be on the order O(log n). At each level, the swap has order O(n^2), so the algorithm has complexity O((n^2)(log n)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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