【问题标题】:C++ Binary Search FunctionC++ 二分查找函数
【发布时间】:2014-11-13 04:43:22
【问题描述】:

我正在尝试创建一个二分搜索功能。我用来测试的数组是: {1, 4, 5, 6, 9, 14, 21, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 89}

现在我想我已经涵盖了所有的边界问题,但是搜索 1 和 42 后返回为未找到,我无法解释。

注意:如果 index = -1 表示在数组中没有找到 searchKey

  1. 42 应在第一次传递时作为索引返回。
  2. 应在第四次传递时将 1 作为索引返回。

两者都返回 index = -1

int BinSearch(int data[], int numElements, int searchKey)
{
    bool found = false;
    int index;
    int searchStart = 0; 
    int searchEnd = numElements - 1;

    while (!found)
    {
        index = (searchEnd + searchStart) / 2;
        // If searchEnd is next to searchStart then check both to see if either is
        // searchKey
        if ((searchEnd - 1) == searchStart)
        {
            found = true;
            if (searchKey == data[searchStart]) {
                index = searchStart;
            } 
            else if (searchKey == data[searchEnd]) {
                index = searchEnd;
            }
            else {
                index = -1;
            }
        } 
        // If index is less than searchStart or greater than searchEnd then searchKey
        // isn't in the array
        else if (index <= searchStart || index >= searchEnd) {
            found = true;
            index = -1;
        }
        else if (searchKey > data[index]) {
            searchStart = index + 1;
        }
        else if (searchKey < data[index]) {
            searchEnd = index - 1;
        }
        else if (searchKey == data[index]) {
            found = true;
        }
    }
    return index;
}

【问题讨论】:

  • 我怀疑使用std::lower_bound 会被视为作弊。
  • Ummm... 42 的索引为 10。所以它不会在第一次通过时找到它。
  • 19/2 = 9.5 被截断为 9,因为您将其填充为整数。第一次通过时找不到它,因为它在索引 10 处。

标签: c++ search binary binary-search


【解决方案1】:

改变这个:

 if ((searchEnd - 1) == searchStart)

到这里:

 if ((searchEnd - 1) <= searchStart)

当查找 1 时,在第三遍中 searchEnd 将为 3,searchStart 将为 0,因此 index 将为 1。由于您的值在位置 0 上,因此它将在第一遍中将 searchEnd 修改为等于 0。

【讨论】:

  • 或者简单的 if( (searchEnd - 1)
  • 非常感谢。它解决了我的问题。我假设整数向上而不是向下取整,即 4.5 将变为 5 而不是 4。
【解决方案2】:
  1. 在第一次遍历时找不到 42,因为它在索引 10 中,但是您有 searchEnd=19 和 searchStart=0,所以第一个索引是 9。
  2. 我认为真正的问题在于,如果 index == searchStart 或 index == searchEnd 没有先检查 searchKey == data[index],您就退出了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2011-02-08
    • 2021-03-07
    相关资源
    最近更新 更多