0

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

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;
    }
}
4

1 回答 1

0

我想你想要

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);
}

此外,您进行了不必要的检查:

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;
}
于 2013-11-09T23:39:48.173 回答