二进制递归搜索

时间:2013-04-09 16:07:33

标签: java recursion

JAVA家庭作业

有人可以给我一些关于我在这里做错了什么的指示吗?感谢。

16.为练习11(f)编写一个递归解决方案,二进制搜索数组以找到一个Key的值。

public class BinarySearch {
    public static void main(String[] args) {
        public static int BinarySearch(int[] sorted, int first, int upto, int key) {
            if (first < upto) {
                int mid = first + (upto - first) / 2;  // Compute mid point.
                if (key < sorted[mid]) {
                    return BinarySearch(sorted, first, mid, key);
                } else if (key > sorted[mid]) {
                    return BinarySearch(sorted, mid+1, upto , key);
                } else {
                    return mid;   // Found it.
                }
            }
            return -(first + 1);  // Failed to find key
        }
    }
}

1 个答案:

答案 0 :(得分:2)

问题是你在另一个方法中定义了一个方法:

public static void main(String[] args) {
    public static int BinarySearch(int[] sorted, int first, int upto, int key) {

只需将BinarySearch方法移到main方法之外:

public static void main(String[] args) {
    //content of this method
}

public static int BinarySearch(int[] sorted, int first, int upto, int key) {
    //content of this other method
}
相关问题