【问题标题】:Trying to implement the Binary Search algorithm, can't seem to get it to work试图实现二分搜索算法,似乎无法让它工作
【发布时间】:2017-08-27 19:27:52
【问题描述】:

在过去的一个小时里,我一直在尝试让这个二分搜索算法工作,并通过使用可汗学院解释的算法示例,我仍然无法让它工作,它应该输出一个数字但是没发生什么事。可汗学院的例子是这样的:

  1. 令 min = 0 且 max = n-1。
  2. 如果 max
  3. 将猜测值计算为最大值和最小值的平均值,向下取整(使其为整数)。
  4. 如果 array[guess] 等于 target,则停止。你找到了!返回猜测。
  5. 如果guess过低,即array[guess]
  6. 否则,猜测太高了。设置最大值 = 猜测 - 1。
  7. 返回步骤 2。

而我按照步骤写的代码是:

#include <iostream>
int main() {
int arr[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };
int min = 0;
int max = 24;
int guess;
int targetValue = 73;
while (max > min) {
    guess = ((max + min) / 2);
    if (arr[guess] == targetValue) {
        std::cout << guess;
        break;
    }
    else if (arr[guess] < targetValue) {
        min = guess + 1;
    }
    else {
        max = guess - 1;
    }
}
return 0;
}

【问题讨论】:

  • 就像一个注释,你应该写std::cout &lt;&lt; guess &lt;&lt; std::endl,这样输出缓冲区就会被刷新。
  • std::cout &lt;&lt; min &lt;&lt; " " &lt;&lt; max &lt;&lt; std::endl; 添加为while 循环的第一行,它应该可以帮助您进行诊断。您会看到该程序现在在min=max=20 处停止
  • 请注意,“max &lt; min 时停止”与“只要max &gt; min 继续”不同。 a b。
  • 最简单的可能是找到成千上万的二进制搜索实现之一并将您的代码与之进行比较。更好的选择是调试您的代码。

标签: c++ arrays algorithm binary-search-tree


【解决方案1】:

二分搜索算法状态

如果 L > R,则搜索不成功而终止。

然而,在您的实现中,您终止了条件 L >= R 的搜索。在 L == R 的情况下,算法应该再进行一次迭代,因为它还没有考虑列表中的这个位置。

在您的目标值为 73 的情况下,当算法到达目标位置 20 时,L == R。您的实现过早终止了一步,无法识别目标。

【讨论】:

    【解决方案2】:

    试试这个:

    (max > min) 到 (max >= min)

    【讨论】:

      猜你喜欢
      • 2017-01-06
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 2011-11-30
      • 2015-09-20
      • 2011-11-01
      • 1970-01-01
      相关资源
      最近更新 更多