java - How can i solve this recursion -


this code find peak number of array integer numbers problem 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 number bigger neighbors , if @ end of array or @ beginning have previews element.

i think error because if element in last position bigger previews peak. example last position 9 have myarray[9] > myarray[8] peak, in first if statement myarray[9+1] don't have gives me error.

i can't remove && first statement , add "or" (||) because wrong answer. ideas please?

just said, problem implementation tries @ index mid + 1, when mid last item in array. need handle case. following:

public long divideandconquer(int lo,int hi){     int mid = (lo+hi) / 2; //modified select middle item     if(mid + 1 >= myarray.length){         //todo: handle case when mid index of last item in array     } else if(mid - 1 < 0){         //todo: handle case when mid index of first item in array     } else 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 long.min_value; //probably more suitable error indicator 99     //alternatively, exception thrown } 

if use approach suggested above, particularly careful when implementing handling of mid - 1 < 0 , mid + 1 >= myarray.length cases. might need special handling of cases when myarray.length 1 or 2.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -