The following code is how I’m trying to create a recursive binary method..
public static int binarySearch(Comparable[] objArray, Comparable item)
{
int lower=0;
int upper=objArray.length -1;
int i = -1;
int compareResult;
boolean found = false;
while ((lower<=upper) && (!found))
{
i=(lower+upper)/2;
compareResult=item.compareTo(objArray[i]);
if(compareResult<0)
{
upper=i-1;
}
else
if (compareResult>0)
{
lower=i+1;
}
else
{
found=true;
}
}
return compareResult;
}
I feel as thought I’m not doing this correctly…any suggestions?
-D
You are using a loop. In order for your method to be recursive, it needs to call itself until it reaches some breaking condition.
Check out Wikipedia’s example.
Essentially, your “while” condition will be the condition that breaks your recursion (i.e. stops the method from calling itself), and the contents of your current loop will instead be setting up the “upper” and “lower” parameters for the next recursive call.