recursion - Finding the max number with Divide and Conquer in Java -
i'm trying find maximum number in array using divide , conquer method(recursion). when compile code, i'm getting arrayindexoutofbounds exception.
i'm not sure i'm going wrong. here code snippet:
public class ... { int[] = {2,4,5,1,6,7,9,3}; int max; public void solution() { max = findmax(0, a.length-1); //print max } private int findmax(int a, int b){ if(b-a == 1){ return a[a]>a[b] ? a[a] : a[b]; } else if(a==b){ return a[a]; } return findmax(findmax(a, (a+b)/2), findmax((a+b)/2 +1, b)); } }
the problem in last line:
return findmax(findmax(a, (a+b)/2), findmax((a+b)/2 +1, b));
this use results of findmax()
methods arguments findmax()
call, means used indexes array. give wrong result or cause arrayindexoutofboundsexception
.
what want return maximum of 2 findmax()
calls:
return math.max(findmax(a, (a+b)/2), findmax((a+b)/2 + 1, b));
Comments
Post a Comment