递归Java递归二进制搜索帮助
下面的代码是我如何创建递归二进制方法的
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;
}
我觉得我做得不对。。。有什么建议吗
-D
# 1 楼答案
你正在使用一个循环。为了使您的方法是递归的,它需要调用自己,直到达到某种中断条件
看看Wikipedia's example
基本上,“while”条件将是中断递归的条件(即停止方法本身的调用),而当前循环的内容将为下一次递归调用设置“upper”和“lower”参数