繁体   English   中英

Ruby 二进制搜索代码未返回预期结果

[英]Ruby Binary Search Code is Not Returning Expected Results

我正在尝试在 Ruby 中编写二进制搜索方法,并且发现了一种奇怪的情况,当我将两个数字相加并在 elsif 语句中将它们除以 2 时,我的代码没有返回我期望的结果。

当我给该方法一个 1-3 的目标和一个 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 的数组时,该方法有效,我得到了我想要的目标的索引.

当我给该方法的目标为 4 时,我得到一个无限循环,因为中间 = first + last / 2 代码返回 5 而不是预期的 3。我什至尝试打印 7/2 结果并得到 3,但是当它拉入值时,它返回 5。

当我为该方法指定 7-10 的目标时,它会中断并说在第 12 行(这是 elsif 所在的行)有一个未定义的方法 '<' 用于 nil:NilClass。


def binary_search(target, array)
  middle = array.length / 2
  first = 0
  last = array.length - 1

  while first < last
    if array[middle] == target
      puts "we've found the target! middle is #{middle}"
      return true
    elsif array[middle] < target
      first = middle + 1
      middle = first + last / 2
      puts "we're in the elsif and middle is #{middle}"
    else
      last = middle - 1
      middle = first + last / 2
      puts "we're in the else and middle is now #{middle}"
    end
  end
  false
end

binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

一个先决条件:

  • 4 + 4 / 2将给我们 6。它相当于4 + (4 / 2 )
  • (4 + 4) / 2将给我们 4。

两种说法不等价。

关于两个中间计算:

middle = first + last / 2

我们没有我们所期望的。

您希望将firstlast除以二。 所以你会想要:

middle = (first + last) / 2

如果您将first + last / 2替换为(first + last) / 2 ,您的脚本将为我们提供:

binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
we're in the else and middle is now 2
we're in the elsif and middle is 3
we've found the target! middle is 3
 => true 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM