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.