This code is to find a peak number of an array with integer numbers
The problem is that i get an error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
.
public long DivideAndConquer(int lo,int hi)
{
int mid=((lo+hi)-1)/2;
if(myarray[mid]>=myarray[mid-1]&&myarray[mid]>= myarray[mid+1])
return myarray[mid];
else if (myarray[mid-1]>= myarray[mid])
return DivideAndConquer(lo,mid-1);
else if (myarray[mid]<=myarray[mid+1])
return DivideAndConquer(mid+1,hi);
return 99;
}
A peak number is a number which is bigger than their neighbors and if I am at the end of the array or at the beginning then I have to look only for the previews element.
I think I get this error because if my element in last position is bigger than previews then is a peak. For example my last position is 9 then I have myarray[9] > myarray[8]
then is a peak, but in the first if statement it look also for myarray[9+1]
which I don't have so it gives me this error.
I can't remove &&
for the first statement and add "or" (||
) because then I get a wrong answer. Any ideas please?