在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
的标准算法是第一个算法,您编写的也是搜索算法,但它不是二进制搜索算法。
他说的对吗?
答案 0 :(得分:1)
您的算法不正确:
案例: 列表[1,2],searchElem = 2,low = 0,high = 1
中=(低+高)/ 2 =(0 + 1)/ 2 = 0
mid 所以您将陷入无限循环。
答案 1 :(得分:0)
我认为您把它弄错了。
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 ) / 2
,lowerBound = midPoint + 1
和upperBound = midPoint - 1
的实际作用。