简体   繁体   English

Java中的二进制搜索结果错误

[英]Wrong result for Binary Search in Java

I am new to programming and wrote this code for recursive binary search, but the output is wrong. 我是编程新手,并为递归二进制搜索编写了此代码,但是输出错误。
I tried debugging it many times but could not know where I am going wrong. 我尝试调试了很多次,但不知道我要去哪里。

public class Number {
    public static void main (String[] args){
        int []a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
        int key = 7;
        int mid,low,high;
        low=0;
        high=a.length-1;
        int pos=binarySearch(a,key,low,high);
        System.out.println(key +" is found at "+pos+" position");
    }

    public static int binarySearch(int[]a,int key,int low, int high) {

        int mid=(low+high)/2;

        if(key<a[mid]){
            high=mid-1;
            binarySearch(a,key,low,high);
        }
        else if(key >a[mid]){
            low=mid+1;
            binarySearch(a,key,low,high);
        }
        else if(low>high){
            return -1;
        }
        return mid;
    }
}

During recursive calls execution of caller is interrupted and his execution frame is pushed onto stack. 在递归调用期间,调用者的执行被中断,并且他的执行帧被压入堆栈。 When callee finishes execution callers frame is retrieved from the stack and his execution proceeds. 当被调用者完成执行时,从堆栈中检索调用者帧,然后继续执行。 You assigned 9 to mid and you returned mid without reassigning it. 您将9分配给中,然后返回中而未重新分配。 If you try different size arrays you will see that always initial mid is returned and all recursive calls are made for no reason. 如果尝试使用其他大小的数组,则会看到始终返回初始中点,并且无缘无故地进行所有递归调用。 To debug place one System.out.println("returning "+mid); 要调试,放置一个System.out.println(“ returning” + mid); in front of return statement. 在return语句前面。

//ignores found value
binarySearch(a,key,low,high);

should be 应该

//returns value
return binarySearch(a,key,low,high);

in both "if" and "else if" clause 在“ if”和“ else if”子句中

You should first check if mid equals key. 您应该首先检查mid是否等于key。 If it does, escape. 如果是这样,请逃脱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM