The following code is how I'm trying to create a recursive 开发者_StackOverflow中文版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.
A guideline to a binary search is to, in this instance, cut the array in half, then check if the comparable object is greater than or equal to the object in the middle of the array. If its smaller you set the upper to one less than the middle (since it has already been checked) and the lower stays the same. If higher, move lower to the middle plus one then the upper stays the same. Keep doing that recursively until you found the object or until it fails when upper == lower.
If you're comparing objects I would write your own compareTo() method in order for you to test if the objects are greater, less or equal to each other.
精彩评论