递归二进制搜索不起作用?

时间:2014-04-08 19:23:46

标签: java recursion

我无法弄清楚为什么我的递归二进制搜索程序无法正常工作。它应该在创建的数组中搜索一个数字,但它返回" Not in List"什么时候。

这是我的IntegerListB类中搜索元素的方法:

public int binarySearchR (int target, int lo, int hi) { 

    if (lo > hi) {
        return -1;
    }

    int middleIndex = lo + ((hi - lo) / 2);
    if (list[middleIndex] == target ) {
        return middleIndex;
    } else if (list[middleIndex] < target) {
        return binarySearchR(target, middleIndex + 1, hi);
    } else {
        return binarySearchR(target, lo, middleIndex - 1);
    }
}

此方法是驱动程序的一部分:

public static void dispatch(int choice) {
    int loc; 
    int size = 0;
    switch(choice) {
        case 0: 
        System.out.println("Bye!"); 
        break; 

        case 1: 
        System.out.println("How big should the list be?"); 
        size = scan.nextInt(); 
        list = new IntegerListB(size); 
        list.randomize(); 
        break; 

        case 2: 
        list.selectionSort(); 
        break; 

        case 3: 
        System.out.print("Enter the value to look for: "); 
        loc = list.linearSearch(scan.nextInt()); 
        if (loc != -1) 
            System.out.println("Found at location " + loc); 
        else 
            System.out.println("Not in list"); 
        break; 

        case 4: 
        System.out.print("Enter the value to look for: ");
        loc = list.binarySearchR(scan.nextInt(), 0, size); 
        if (loc != -1) 
            System.out.println("Found at location " + loc); 
        else 
            System.out.println("Not in list"); 
        break; 

        case 5: 
        list.print(); 
        break; 

        default: 
        System.out.println("Sorry, invalid choice"); 
    } 
} 

是的,其他一切正常。这只是具体的方法。此外,hi表示数组的最大索引,其中lo表示起始索引。

0 个答案:

没有答案