Recursion 递归二进制搜索程序

Recursion 递归二进制搜索程序,recursion,binary-search,Recursion,Binary Search,这是我的递归二进制搜索方法。假设这是从排序列表中查找电话号码,但它只适用于文件中的第一个号码,并且表示其他所有号码都找不到。有人能帮我找出问题所在吗 static int binary (String num, String[] phone, int low, int high) { if ((high - low) <= 1) { if (phone [low].equals (num)) { return low;

这是我的递归二进制搜索方法。假设这是从排序列表中查找电话号码,但它只适用于文件中的第一个号码,并且表示其他所有号码都找不到。有人能帮我找出问题所在吗

static int binary (String num, String[] phone, int low, int high)
{
    if ((high - low) <= 1)
    {
        if (phone [low].equals (num))
        {
            return low;
        }
        else if (phone [high].equals (num))
        {
            return high;
        }
        else
        {
            return -1;
        }
    }
    int mid = (low + high) / 2;
    if (phone [mid].compareTo (num) > 0)
    {
        return binary (num, phone, 0, mid);
    }
    else if (phone [mid].compareTo (num) < 0)
    {
        return binary (num, phone, mid, high);
    }
    else
    {
        return -1;
    }
}
static int binary(String num,String[]phone,int low,int high)
{
如果((高-低)0)
{
返回二进制(num、phone、0、mid);
}
else if(电话[mid]。与(num)<0比较)
{
返回二进制(num、phone、mid、high);
}
其他的
{
返回-1;
}
}
我想你想要

if (phone [mid].compareTo (num) > 0)
{
    return binary (num, phone, low, mid-1);
}
else if (phone [mid].compareTo (num) < 0)
{
    return binary (num, phone, mid+1, high);
}
if(电话[mid]。比较到(num)>0)
{
返回二进制(num、phone、low、mid-1);
}
else if(电话[mid]。与(num)<0比较)
{
返回二进制(num、phone、mid+1、high);
}
此外,您执行的检查也比必要的多:

static int binary (String num, String[] phone, int low, int high)
{
    if(low > high)
    {
        return -1;
    }
    int mid = (low + high) / 2;
    int compare = phone[mid].compareTo(num);
    return compare > 0 ? binary (num, phone, low, mid-1);
        : compare < 0 ? binary (num, phone, mid+1, high);
        -1;
}
static int binary(String num,String[]phone,int low,int high)
{
如果(低>高)
{
返回-1;
}
int mid=(低+高)/2;
int compare=phone[mid].compareTo(num);
返回比较>0?二进制(num、phone、low、mid-1);
:比较<0?二进制(数字、电话、中+1、高);
-1;
}