0

Possible Duplicate:
Stack overflows from deep recursion in Java?

I have written the following method with divide and conquer for my assignment:

calculateC(cMatrix, cMatrix.length - 1, cMatrix.length - 1, w);
    for(int i = cMatrix.length - 2 ;i>=0; i--)
        calculateC(cMatrix, i, i+1, w);

private static double calculateC(double[][] matrix,
    int i,
    int j,
    double[][] w){
    o++;
    double x1 = 0;
    double x2 = 0;
    double result = 0;
    if(i > j) result = 0;
    if(i == j){
        matrix[i][j] = w[i][j];
        result = w[i][j];

    }

    else if(i <= j){

        for(int k = i; k <= j; k++){

            if(i > k - 1)
                x1 = 0;
            else if(i <= k - 1){

                if(matrix[i][k - 1] != 0){
                    x1 = matrix[i][k - 1];
                } else{
                    x1 = calculateC(matrix, i, k - 1, w);

                }
            }
            if(k + 1 > j)
                x2 = 0;
            else if(k + 1 <= j){

                if(matrix[k + 1][j] != 0){
                    x2 = matrix[k + 1][j];

                } else{
                    x2 = calculateC(matrix, k + 1, j, w);
                }
            }

            cs.add(x1 + x2);
            ks.add(k);
        }
        addMin(matrix, i, j, cs, ks, w);
    }

    if(j >= 0 && i >= 0 && j < matrix.length - 1){

        calculateC(matrix, i, j + 1, w);
    }

    return result;

}

This method works on a nn matrix, but for matrixes with n>=10 it causes java.lang.StackOverflowError And it seems to be because of the function calls in this method. I test it for each matrix with n rows and n columns, the recursive method is being called nn times. Is it the reason of exception? How can I solve it? I have written the above method with iterative and it works right but I should write this method with divide and conquer too, I tried hard but I don’t know how to solve the problem.

1

1 Answer 1

3

Either:

  1. Increase the stack size of your VM

  2. Rewrite your code so that you make less recursive calls. It doesn't look like it's doing something where you really need to recurse on every cell of the matrix rather than just on matrices of sizes NxN down to 1x1?

  3. Eliminate the recursion entirely. You can rewrite any recursive function with loops and your own stack management.

Sign up to request clarification or add additional context in comments.

2 Comments

would u please expain the secon guide a little more?
I have increased the size of heap in eclipse to -Xmx512m, but it still cause the same exceptions. should I increase more?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.