简体   繁体   English

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

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

In Binary Search Algorithm , Binary Search Algorithm

in general 一般来说

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

But I've just modified the algorithm like these 但是我已经像这样修改了算法

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

But my teacher told me that the standard algorithm for binary search is the first one and what you have written is also a search algorithm but it's not an algorithm for binary search. 但是我的老师告诉我, binary search的标准算法是第一个算法,您写的也是搜索算法,但它不是二进制搜索的算法。 Is he correct?. 他说的对吗?

Your Algo is not correct : 您的算法不正确:

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

mid = (low+high)/2 = (0+1)/2 = 0 中=(低+高)/ 2 =(0 + 1)/ 2 = 0

mid < searchElem set low = mid updated mid = 0, high = 1 [list didn't change] mid <searchElem设置低=更新中= 0,高= 1 [列表没有变化]

so you will end up with infinite loop. 因此您将陷入无限循环。

I think you picked it up wrongly . 我想你把它弄错了。

The basic Binary Search Algorithm 's workflow: 基本的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

Here you can see what actually midPoint = lowerBound + ( upperBound - lowerBound ) / 2 , lowerBound = midPoint + 1 and upperBound = midPoint - 1 does . 在这里,您可以看到midPoint = lowerBound + ( upperBound - lowerBound ) / 2lowerBound = midPoint + 1upperBound = midPoint - 1作用。

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

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