第 5 个元素的二进制搜索 (Java) 异常

Binary Search (Java) exception on 5th element

方法 binarySearch returns ArrayOutOfBounds 异常,当我创建一个包含 5 个元素的数组并搜索第 5 个元素时。所有其他测试用例都可以正常工作,最多 10 个元素。

即使我使用 if-else 循环也会遇到此错误。有人有解释和解决方案吗?

    private static int[] arrayEntry() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the size of the array: ");

        int size = scan.nextInt();
        int[] arr = new int[size];
        System.out.println("Enter the items of the array: ");
        for(int i=0; i<size; i++){
            arr[i] = scan.nextInt();
        }

        return arr;
    }

        //code for choice menu

            case 2:
                Arrays.sort(arr);
                System.out.println("Enter the item to be searched: ");
                searchItem = scan.nextInt();
                int result = binarySearch(arr, searchItem);

                if (result!=-1){
                    System.out.println("Item found at index: "+ result+ " (index starting at 0).");
                }else System.out.println("Item not found!");

                break;

    private static int binarySearch(int[] arr, int searchItem) {

        int lastItem = arr.length-1;
        int startItem = 0;

        while(startItem<=lastItem){
            int midValue = startItem + (lastItem-1)/2;

            if (searchItem == arr[midValue]){
                return midValue;
            }

            if (searchItem>arr[midValue]){
                startItem = midValue+1;
            }else lastItem = midValue-1;
        }return -1;
    }

}

试试这个

public int runBinarySearchIteratively(
 int[] sortedArray, int key, int low, int high) {
 int index = Integer.MAX_VALUE;

 while (low <= high) {
    int mid = (low + high) / 2;
    if (sortedArray[mid] < key) {
        low = mid + 1;
    } else if (sortedArray[mid] > key) {
        high = mid - 1;
    } else if (sortedArray[mid] == key) {
        index = mid;
        break;
    }
}
return index;
}

来源:http://www.baeldung.com/java-binary-search