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

时间:2018-03-30 23:12:28

标签: java binary-search

当我创建一个包含5个元素的数组并搜索第5个元素时,方法binarySearch返回ArrayOutOfBounds异常。所有其他测试用例最多可以处理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;
    }

}

1 个答案:

答案 0 :(得分:0)

试试这个

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