Reputation: 89
In 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.
Is he correct?.
Upvotes: 0
Views: 149
Reputation: 9
Your Algo is not correct :
case : list [1, 2] , searchElem = 2 , low = 0,high = 1
mid = (low+high)/2 = (0+1)/2 = 0
mid < searchElem set low = mid updated mid = 0, high = 1 [list didn't change]
so you will end up with infinite loop.
Upvotes: 1
Reputation: 445
I think you picked it up wrongly .
The basic Binary Search Algorithm
's workflow:
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 .
Upvotes: 0