簡體   English   中英

第5個元素上的二進制搜索(Java)異常

[英]Binary Search (Java) exception on 5th element

當我制作一個由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;
    }

}

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM