1

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.

pat
  • 12,587
  • 1
  • 23
  • 52
d3vcho
  • 85
  • 7

2 Answers2

1

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


Two ways:

  1. Master Theorem

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

    Since, Logba == c, this falls under the case 2, resulting in the complexity of O(ncLog n) = O(n2 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 n2 (at each level).

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

    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 Log2n.

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

displayName
  • 13,888
  • 8
  • 60
  • 75
0

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)).

pat
  • 12,587
  • 1
  • 23
  • 52