递归二进制搜索程序

时间:2013-11-09 23:30:57

标签: 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;
        }
        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;
    }
}

1 个答案:

答案 0 :(得分: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;
}