Hi there ive got a search algoritm that gets stuck as it att

 Hi there, ive got a search algoritm that gets stuck as it attempts to cycle through to determine if a number is within a list. unfortunately, it gets stuck with a stack overflow error.  can anyone point out my mistake and if possible, explain what i did wrong?    public static <T extends Comparable<? super T>> boolean trinarySearch(T[] a, T desiredItem, int n) {     // it is assumed that the data is already sorted     return trinarySearch(a, 0, n-1, desiredItem); } // end trinarySearch    public static <T extends Comparable<? super T>> boolean trinarySearch(T[] a, int left, int right, T desiredItem ) {     boolean exist=false;     int mid1=left+(right-left)/3;     int mid2=right-(right-left)/3;     int comparetovalue1=desiredItem.compareTo(a[mid1]);     int comparetovalue2=desiredItem.compareTo(a[mid2]);     if (comparetovalue1<0)// desired item is less than mid 1     {         return  trinarySearch(a,0,mid1,desiredItem);     }     else if (comparetovalue1>0 && comparetovalue2<0) //desired item is greater than mid2     {         return  trinarySearch(a,mid1,mid2,desiredItem);     }     else if (comparetovalue2>0)// desired is in between mid 1 and mid2     {         return trinarySearch(a,mid2,a.length,desiredItem);     }     else if (comparetovalue1==1 || comparetovalue2==1)     {          exist=true;     }     return exist;     //System.out.println(\"recursive trinarySearch method  - IMPLEMENT ME\"); } // end trinarySearch 

Solution

look at \"else if\" condition just before it,  

If compareToValue2 is equal to 1, then condition B will be true i.e. it never reaches condition A. I don\'t know about how java works, but I think you need to change condition B to comparetovalue2 > 1 or something of sorts   and similarly check other if, else if conditions

 Hi there, ive got a search algoritm that gets stuck as it attempts to cycle through to determine if a number is within a list. unfortunately, it gets stuck wit

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site