binarySearch Method producing “ArrayIndexOutOfBoun

2019-08-20 03:34发布

问题:

I would like to know why this method is giving me an ArrayIndexOutOfBounds exception when I provide a key that is a letter not in my array. It seems to have no problem returning a value if the key is anything other than a letter.

public class BinarySearch2 {

    public static void main(String[] args) {
        String[] array = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
        String key = "K";
        String found = binarySearch(array, key);
        System.out.println(found);
    }

    public static String binarySearch(String[] array, String key) {
        int low = 0;
        int high = array.length;
        int mid = (low + high)/2;
        //int i = 0;

        while (low <= high) {
            //System.out.print(i + " ");
            if (array[mid].compareTo(key) < 0) {
                System.out.println(array[mid].compareTo(key));
                low = mid + 1;
                mid = (low + high)/2;
            }
            else if (array[mid].compareTo(key) > 0) {
                high = mid - 1;
                mid = (low + high)/2;
            }
            else
                return array[mid];

            //i++;
        }
        return "-1";
    }
}

回答1:

In your binarySearch method, you have initialized your high to: -

int low = 0;
int high = array.length;
int mid = (low + high)/2;

Your high should actually be: -

int high = array.length - 1;