使用数组在C ++中进行二进制搜索

时间:2013-07-29 16:16:09

标签: algorithm binary-search

这是一个包含15个元素的数组:

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

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

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

我是对还是不对?

2 个答案:

答案 0 :(得分:2)

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

其他2将是4和12。

正确答案是4,8,12

答案 1 :(得分:0)

`我发现答案是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`
  

块引用