java 中的二进制搜索代码错误

Error in code of Binary Search in java

我在 java.I 中进行二进制搜索,希望将数组和键值作为用户输入,所以我在这里使用扫描仪。

I have written this code but cannot understand why it doesn't work when I give the key value as user input.I know what is binary search and have gone through the other questions already on Stack Overflow,but mine is a coding problem which I cannot figure out so if anyone could help.My code is:

//Program for getting a key value doing Binary Search
import java.util.Scanner;

public class Bin_Search{

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int a[] = new int[n];
    for(int i =0; i<n; i++)
        a[i]= scan.nextInt();
    for(int i =0; i<n; i++)
        System.out.print(a[i] + " ");
    System.out.println("Enter the value you want to find");
    int key = scan.nextInt();
    Bin_Search bin = new Bin_Search();
    System.out.println("position is" + bin.b_search(a,key));
}

//Method to perform binary search
public int b_search(int arr[], int key)
{
    int n = arr.length-1;
    int lo = 0;
    int hi = n-1;
    int mid = (lo+hi)/2;
    while(lo<=hi)
    {
        if(a[mid]>key)
            hi = mid-1;
        else if(a[mid]<key)
            lo = mid+1;
        else 
            return mid;
    }
    return -1;
}
}

你永远不会改变mid,你将在无限循环中检查数组中的相同位置。您需要在循环的每次迭代中更改它

while(lo<=hi)
{
    if(a[mid]>key)
        hi = mid-1;
    else if(a[mid]<key)
        lo = mid+1;
    else 
        return mid;

    mid = (lo+hi)/2;
}

顺便说一句,你遗漏了数组中的最后一项

int n = arr.Length - 1;
int hi = n - 1;

意味着hi实际上是arr.Length - 2。就这样

int hi = arr.Length - 1;