Hi, I have this bit of code to do some testing before I implement it. Basically on the second recursive call it should enter in on this line ( else if( sec >= 1 ) { return test( s ,lowerBounds + middle + 1, upperBounds ); } ) but it does not instead it goes on to the other else if and changes the value of sec. Am I missing something?
public class Main
{
private static String[] test = { "aaa", "aab", "aac", "aad", "aae" };
public static void main( String[] args ) {
System.out.println( test( "aab", 0, 4 ) );
}
public static int test( String s, int lowerBounds, int upperBounds ) {
if( upperBounds < lowerBounds || upperBounds > lowerBounds ) {
int middle = ( upperBounds – lowerBounds ) / 2;
int sec = s.compareTo(test[lowerBounds + middle]);
if( sec == 0 )
{ return lowerBounds + middle; }
else if( sec <= -1 )
{ return test( s, lowerBounds, upperBounds – middle – 1 ); }
else if( sec >= 1 )
{ return test( s ,lowerBounds + middle + 1, upperBounds ); }
} else { return -1; }
return -10;
}
}
EDIT: Sorry I should have said this is my own implementation of binary searching. I am still learning programming on my own so please do not flame me if I have messed it up somehow.
EDIT: If I remove the first if statement it looks as though it works fine?