【问题标题】:Binary Search in C++ with arrayC++中使用数组的二分搜索
【发布时间】:2018-02-22 02:11:01
【问题描述】:

这是一个正好有 15 个元素的数组:

1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

假设我们正在对一个元素进行二分搜索。通过检查数组中的两个或更少的数字来指示将找到的任何元素。

我得到了什么:因为我们正在进行二进制搜索,所以仅通过一次比较找到的数字将是第 7 个元素 = 7。对于两次比较,这会导致数组的第二次划分。也就是说,找到的数字可以是 3 或 11。

我是对还是错?

【问题讨论】:

  • 听起来对我来说是正确的,可能需要添加一个假设,即在将偶数数组分成两半时,您使用的是两个可能数字中较小的一个。
  • 是的,这会引导您进行两个比较,但有时数组不会被排序,您可能需要先排序。
  • 鉴于问题描述中的数组,它实际上是4 8 12
  • arr[7] = 8,这可能会导致您的困惑。您说的是第 7 个元素,您可能是指 7 处的元素。

标签: algorithm binary-search


【解决方案1】:

你几乎是对的,第一个数字不是七而是八。

其他 2 将是 4 和 12。

正确答案是 4、8、12

【讨论】:

  • 感谢大家的快速回复
【解决方案2】:

`我发现答案是 8,即第 7 个元素,找到的其他元素是排序数组的第 3.5 个和第 10.5 个元素。因此,接下来研究的两个数字是 4 和 11。

解释我是如何得到答案的。
给定数组是 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

head=1
tail=15
middle= 0+14/2=7th element **0 is the index value of 1 and 14 is of 15**    
middle value turns to be 8 as it is the 7th element.

solving value for first half
head=1
tail=8
middle= 0+7/2=3.5 or 3rd element **0 is the index value of 1 and 7 is of 8**

middle value now turns to be 4 as it is the 3rd element.

solving value for second half
head=8
tail=15
middle= 7+14/2=10.5 or 10th element  **7 is the index value of 8 and 14 is 
of 15**

middle value now turns to be 11 as it is the 10th element of the array`

块引用

【讨论】:

  • 关于如何获得答案的解释,对其他用户来说会很好。
猜你喜欢
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 2015-04-13
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多