I am writing a divide and conquer recursive function to find minimum element in array. But I am getting java.lang.StackOverflowError . Here is my code. Thanks in advance.
import java.util.Scanner;
public class dynamic {
public static void main(String arg[])
{ int i=0;
Scanner s=new Scanner(System.in);
int num[]=new int[8];
while(i<8)
{
num[i]=s.nextInt();
i++;
}
int b=findmin(num);
System.out.println(b);
}
public static int findmin(int num[])
{
if(num.length==0)return 0;
return findmin(num,0,num.length-1);
}
public static int findmin(int num[],int first,int last)
{
if(first==last )return num[first];
if(first+1==last)return Math.min(num[first],num[last]);
if(findmin(num,(last/2)+1,last)>findmin(num,first,last/2)) return findmin(num,first,last/2);
else return findmin(num,(last/2)+1,last);
}
}
first of all there is no use calculating the minimum by divide and conquer,the algorithm is still O(N).
secondly while dividing [first,last] the division is [first,(first+last)/2] & [(first+last)/2+1,last].
third point is that you are calling the function for same arguements twice, when you are comparing & when you return.
if(findmin(num,(last/2)+1,last)>findmin(num,first,last/2))
return findmin(num,first,last/2);
else return findmin(num,(last/2)+1,last);
take care of the second point and your code will run ,atleast for small inputs
I updated your code a little - added logging, please see the output…
1 Like
I am using divide and conquer here just for learning purpose, and thanks for ur help. I will check if this works.
1 Like
Thanks , but u have modified my function completely so I have to understand it. Please tell me what that printspaces doing ?
yeah this worked!!!THANKS
It’s just logging recursive function calls printSpaces is doing indentation, to see how the the function was called. I’m using this approach when debugging some difficult problems - it’s easy to do some mistake somewhere and when it is in 5-th level of recursion debugging is like waste of time…
If I have some time, I’ll modify your working solution to show you the output…