首页 文章

二进制搜索无法找到目标号码

提问于
浏览
-1

我无法理解为什么我的binarySearch方法无法找到所需的目标号码 . 例如main方法,我使用了3长度数组(1,2,3)和目标数字3.在二进制搜索方法中,在一个点上,start和end变量将等于2(2,表示索引值) . 在我的代码中,我有一个条件,如果开始和结束彼此相等,它将检查源[mid]是否等于2,它应该是 . 然后它将返回true . 但我不明白为什么它不会回归真实 .

public class Searches {

public static boolean binarySearch(int[] source,int start, int end, int target)
{
    int mid = start + (end - start) / 2;


    if (start == end)
    {
        if (source[mid] == target) return true;

    }



    if (target < source[mid])
        {
            end = mid - 1;
            binarySearch(source,start, end,target);
        }
    else if (target > source[mid])
        {
            start = mid + 1;
            binarySearch(source, start, end, target);
        }
    else return true;




    return false;
}



public static void main(String[] args)
{
    int[] b = {1,2,3};
    System.out.println(binarySearch(b,0,b.length-1, 3));    
}

 }

1 回答

  • 2

    因为这似乎是功课:

    删除函数末尾的 return false ,然后修复编译器错误,而不添加另一行代码 .

    在进行更改后,Quirliom的评论意味着什么 .

相关问题