我的java二进制搜索代码有什么问题?

时间:2014-12-07 00:36:10

标签: java while-loop binary-search

我想我在二进制搜索代码中处于无限循环中。我在empID中传递,因此它可以返回mid的下标,但不返回任何内容。

public int binSearch(int empID)
{
    int first = 0;
    int last = empCount - 1;
    int found = 0;
    int mid = 0;

    while (first <= last && found == 0)
    {
        mid = (first + last) / 2;

        if (empNums[mid] == empID)
        {
            found = 1;
        }
        else
        {   
            if (empNums[mid] < empID)
            {
                first = mid + 1;
            }
            else
            {
                last = mid - 1;
            }
        }
        while (found == 0)
        {
        mid = -1;
        }

    }
    return mid;

}

3 个答案:

答案 0 :(得分:1)

我真的不明白为什么你把while(found==0)循环放在函数的中间,但它肯定会导致无限循环。只需尝试删除它。为了知道是否找到了解,我们可以在这种特殊情况下使方法返回-1。只需在功能结束时检查此条件。 在计算中间索引时,我也进行了逻辑右移位。

public int binSearch(int empID)
{
    int first = 0;
    int last = empCount - 1;
    boolean found = false;
    int mid = 0;

    while (first <= last && !found)
    {
        mid = (first + last) >>> 1; // overflow prevention

        if (empNums[mid] == empID) {
            found = true;
        } else if (empNums[mid] < empID) {
            first = mid + 1;
        } else {
            last = mid - 1;
        }
    }
    return found ? mid : -1;
}

答案 1 :(得分:0)

让我们看看这个场景: 你的第一个是0而你的结尾是1。 那么你有这个: mid = 1 + 0/2 永远是0!这可能会导致问题,因为你可以一遍又一遍地检查同一个位置。

尝试使用Math.Ceil方法,当你到达中间时:

Mid = Math.Ceil(start + end)/ 2); 你可能需要施展!! 祝你好运

答案 2 :(得分:0)

我会建议:

public int binSearch(int empID)
{
    int first = 0;
    int last = empCount - 1;
    int mid;

    // check the first and last element, otherways it could take too long to get to them
    if (empNums[first] >= empID) 
        mid = first;
    else if (empNums[last] <= empID)
        mid = last;
    else 
        do {
            mid = (first + last) / 2;
            // If you have found an element, just return it, no found variable is required     
            // And you do not want to add or subtract 1 from a limits, because 
            // next element could be one you looking for 
            if (empNums[mid] == empID)
                return mid;
            else if (empNums[mid] < empID)
               first = mid;
            else
                last = mid;
        } while (first < last);

    // optional check to see that correct parameter has been found
    if (empNums[mid] != empID) {
       // do something
    }

    return mid;
}
相关问题