【问题标题】:Recursive binary search program递归二分查找程序
【发布时间】:2013-11-09 23:30:56
【问题描述】:

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

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

【问题讨论】:

    标签: recursion binary-search


    【解决方案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);
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-16
      • 2012-12-19
      • 1970-01-01
      • 2020-11-13
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多