首页 文章

通用数组上的二进制搜索返回前两个索引或Stackoverflow异常

提问于
浏览
1

家庭作业问题!我们正在使用带有通用数组和比较器的二进制搜索 . 赋值需要我们有Integer / Double / String类型数组,我们可以使用二进制搜索搜索每个数组 . 我以前在非通用阵列上成功使用了二进制搜索,但这有点困难 . 我在调用搜索之前生成我的Arrays,提示用户进行选择,然后执行搜索(这就是想法) . 目前正在实施Binary Search SORT的工作 . 它将在前两个索引位置找到关键字...在中间范围索引上抛出一个stackoverflow异常,高端索引不返回任何内容,输入未找到吐出-1(我将在二进制搜索工作时添加一个输出) . 我知道问题在于我如何实现二进制搜索,我只是没有解决它 . 任何帮助,将不胜感激 . 代码如下:

public static void searchIntegers() {
    System.out.print("Please enter the Integer you would like to search for: ");
    try {
        keyInt = input.nextInt();
        System.out.print(keyInt + " is found in index " + binarySearch(integerArray, keyInt));
    }
    catch (InputMismatchException inputMismatchException) {
        input.nextLine();
        System.out.printf("Please enter only Integers. Try again. \n\n");
    }  
}
    public static <E extends Comparable<E>> int binarySearch(E[] list, E key) {
    return binarySearch(list, key, 0, list.length);
}
public static <E extends Comparable<E>> int binarySearch(E[] list, E key, int low, int high) {
    int mid = low + high / 2;

    if (low > high) {
        return -1;
    }
    else if (list[mid].equals(key)) {
        return mid;
    }
    else if (list[mid].compareTo(key) == -1) {
        return binarySearch(list, key, mid +1, high);
    }
    else {
        return binarySearch(list, key, low, mid -1);
    }
}
    public static void generateArrays() {
    //GENERATE INTEGER ARRAY
    for(i = 0; i < 10; i++) {
        integerArray[i] = generator.nextInt(100);
    }
    Arrays.sort(integerArray);
    //GENERATE DOUBLE ARRAY
    for(i = 0; i < 10; i ++) {
        doubleArray[i] = i + generator.nextDouble();
    }
    Arrays.sort(doubleArray);     
}

1 回答

  • 0

    它基本上在检查低和高并进入循环时失败

    试试这个 -

    public static <E extends Comparable<E>> int binarySearch(E[] list, E key, int low, int high) {
    
    
        int mid = (low + high) / 2;
    
        if (low > high) {
            return -1;
        }
    
        if (list[mid].equals(key)) {
            return mid;
        } else if (list[mid].compareTo(key) == -1) {
            return binarySearch(list, key, mid + 1, high);
        } else {
            return binarySearch(list, key, low, mid - 1);
        }
    }
    

    您需要在中间计算中添加括号 . 只是一个建议,检查溢出条件 .

相关问题