繁体   English   中英

有关使用C进行二进制搜索的算法的查询

[英]A query regarding the algorithm of binary search using C

Binary Search Algorithm

一般来说

if   mid_value > search_element we set high = mid_pos-1 ;
else mid_value < search_element we set  low = mid_pos+1 ;

但是我已经像这样修改了算法

if   mid_value > search_element we set high = mid_pos ;
else mid_value < search_element we set  low = mid_pos ;

但是我的老师告诉我, binary search的标准算法是第一个算法,您写的也是搜索算法,但它不是二进制搜索的算法。 他说的对吗?

您的算法不正确:

case:list [1,2],searchElem = 2,low = 0,high = 1

中=(低+高)/ 2 =(0 + 1)/ 2 = 0

mid <searchElem设置低=更新中= 0,高= 1 [列表没有变化]

因此您将陷入无限循环。

我想你把它弄错了。

基本的Binary Search Algorithm的工作流程:

Procedure binary_search
   A ← sorted array
   n ← size of array
   x ← value to be searched

   Set lowerBound = 1
   Set upperBound = n 

   while x not found
      if upperBound < lowerBound 
         EXIT: x does not exists.

      set midPoint = lowerBound + ( upperBound - lowerBound ) / 2

      if A[midPoint] < x
         set lowerBound = midPoint + 1

      if A[midPoint] > x
         set upperBound = midPoint - 1 

      if A[midPoint] = x 
         EXIT: x found at location midPoint
   end while

end procedure

在这里,您可以看到midPoint = lowerBound + ( upperBound - lowerBound ) / 2lowerBound = midPoint + 1upperBound = midPoint - 1作用。

暂无
暂无

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

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