binarySearch方法产生“ArrayIndexOutOfBounds”异常

时间:2012-10-10 19:27:25

标签: java exception methods binary-search indexoutofboundsexception

我想知道为什么当我提供一个不在我的数组中的字母时,这个方法给了我一个ArrayIndexOutOfBounds异常。如果键不是字母,那么返回值似乎没有问题。

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 个答案:

答案 0 :(得分:2)

binarySearch方法中,您已将high初始化为: -

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

实际应该是: -

int high = array.length - 1;