简体   繁体   English

Java:递归二进制搜索以查找数组的元素-逻辑错误

[英]Java:Recursion Binary search to find element of an array-Logical error

I am trying to find an element in an array using binary search-recursion. 我正在尝试使用二进制搜索递归在数组中查找元素。 I am unable to figure what is wrong with the logic in the program as I am getting incorrect output. 由于输出不正确,我无法弄清楚程序中的逻辑出了什么问题。 Say if I search for 5, the output I am getting is 4. Similarly I am not getting correct results for other cases as well. 假设我搜索5,得到的输出是4。同样,在其他情况下,我也没有得到正确的结果。 What might be the problem with this program ? 该程序可能是什么问题?

public class OrdArray {
    private long[] a;
    private int nELems;


    public OrdArray(int max){


    a=new long[max];
        int nElems=0;
    }

    public int size(){
        return nELems;
    }

    public void insert(int value){
        int j;
        for(j=0;j<nELems;j++){
            if(a[j]>value){
                break;
            }
        }
        for(int k=nELems;k>j;k--){
            a[k]=a[k-1];
        }
        a[j]=value;
        nELems++;
    }

    public void display(){
        for(int i=0;i<nELems;i++)
        System.out.print(a[i]+" ");
        System.out.println(" ");
    }

    public int Recursionfind(int low,int high,int key){

        if(low>=high){
            return nELems;
        }

        int mid=(low+high)/2;

        if(a[mid]== key){
            return mid;
        }

        if(a[mid]>key){
            return Recursionfind(low,mid-1,key);
        }

        else{
            return Recursionfind(mid+1,high,key);
        }

    }
}


class OrderedApp{
    public static void main(String[] args) {
        int maxsize=100;
        OrdArray arr;
        arr=new OrdArray(maxsize);
        System.out.println("Insert array:");
        arr.insert(3);
        arr.insert(5);
        arr.insert(1);
        arr.insert(7);
        arr.insert(6);
        arr.insert(4);
        arr.insert(8);
        arr.insert(2);
        arr.insert(9);
        arr.display();
        int n=arr.size();
        System.out.println(n);
        int key=5;

        System.out.println("Key is :" + arr.Recursionfind(0,n-1,key));
    }
}

The error lies here: 错误在这里:

if(a[mid]== key){
    return mid;
}

You match the searched value to the value of your array at place mid . 您在匹配的地方搜索价值,你的阵列的价值mid If you find it you have to return the found value not the key. 如果找到它,则必须返回找到的值而不是键。

if(a[mid]== key){
    return a[mid];
}

You also have to change a from long[] to int[] . 您还必须将along[]更改为int[]

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

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