[英]Using recursive algorithm for binary search
Help me.帮我。 I am a newbie to java and I am stuck in binary search recursion (stackoverflow error) and I can't find solution anywhere.
我是 java 的新手,我陷入了二进制搜索递归(stackoverflow 错误),在任何地方都找不到解决方案。
public class BinarySearch {
public static int binAry (int ary[], int st, int lt, int val){
if (st<=lt) {
int mid = (st + (lt-st)) / 2;
if (val > ary[mid]) {
binAry(ary, mid+1, lt, val);
}
else if (val < ary[mid]) {
binAry(ary, st, mid-1, val);
}
else{
return mid;
}
}
return -1;
}
public static void main (String[] args){
BinarySearch bs = new BinarySearch();
int [] numbers = {0,1,2,3,4,5};
int x = 3;
int pt = numbers.length;
int p = bs.binAry(numbers, 0, pt-1, x);
if (p == -1){
System.out.println("Number not found.");
}
else{
System.out.println("Number found at " + p);
}
}
}
For what I see, the problem is that (val > ary[mid]) will always evaluate to true.就我所见,问题在于(val > ary[mid])将始终评估为真。 Always.
总是。 Thus your code will enter an endless loop, which, ultimately, results in a StackOverFlow exception.
因此,您的代码将进入无限循环,最终导致 StackOverFlow 异常。
If you follow the value of the variables involved in your code to that point, you will notice that val never changes, being its value 3 since the beginning.如果您跟踪代码中涉及的变量的值,您会注意到val从未改变,从一开始就是它的值 3。
Also, int mid = (st + (lt-st)) / 2 is the same as lt/2 because st + (lt - st) = st - st + lt (do the test by assigning them whatever values you want).此外, int mid = (st + (lt-st)) / 2与lt/2相同,因为 st + (lt - st) = st - st + lt (通过为它们分配您想要的任何值来进行测试)。 So even though you change the value of st in binAry(ary, mid+1, lt, val) , it really has no effect.
因此,即使您更改了 st 在binAry(ary, mid+1, lt, val)中的值,它确实没有任何效果。 lt will always be numbers.length - 1 and mid will always be 5/2=2.
它永远是numbers.length - 1 , mid永远是 5/ 2 =2。
Add this code right below int mid = (st + (lt-st)) / 2 to check for yourself:在int mid = (st + (lt-st)) / 2正下方添加此代码以自行检查:
System.out.println("st="+st);
System.out.println("lt="+lt);
System.out.println("mid="+mid);
Maybe if you explained what you want to do I would understand this a bit better and perhaps I'd be able to actually help find a solution.也许如果你解释了你想做什么,我会更好地理解这一点,也许我能够真正帮助找到解决方案。
Edit: Ok, after dedicating it a bit more time I found your error.编辑:好的,在花费更多时间之后,我发现了您的错误。 Change the formula:
更改公式:
int mid = (st + (lt-st)) / 2 // This is wrong
int mid = st + (lt-st) / 2; // This is ok, notice the parentheses
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.