0

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?.

5
  • Possible duplicate of Where can I get a "useful" C++ binary search algorithm? Commented Oct 30, 2018 at 5:51
  • 2
    This is also binary search. It is just that we set the position as (mid-1) or (mid+1) because we do not need to check the middle element again in the next condition because it was already done in the previous one. The runtime is more or less the same in either case. Commented Oct 30, 2018 at 5:52
  • Did you know , what actually mean by high = mid_pos-1 ,low= mid_pos+1 ? . Please, first understand the basic structure and flow of position . Commented Oct 30, 2018 at 5:56
  • The difference is that the first one reduces the range by one more than your algorithm does, and therefore potentially finish faster. Commented Oct 30, 2018 at 6:31
  • One difference is that, if you're not careful, the second one can easily get into an infinite loop . . . Commented Oct 30, 2018 at 7:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually in my algorithm high is initiated by length of the list
0

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.