Lamentis's blog

By Lamentis, history, 9 months ago, In English

Can someone explain when to use which variation of equality in Binary Search:

1.)while(l<=r) 2.)while(l<r) 3.)while(r-l>1)

Generally, I use the first one as it seems to be the most comfortable for me. However, when going through other participants' codes, I often see the other two variations. Is there any difference?

  • Vote: I like it
  • +2
  • Vote: I do not like it

»
9 months ago, # |
Rev. 5   Vote: I like it 0 Vote: I do not like it

Well, of course there is a difference, because l <= r and l < r and r - l > 1 are not logically equivalent. Different terminating conditions correspond to different implementations of binary search, or different uses of binary search (finding the largest or smallest value that satisfies a condition often has a different ending condition than just finding any value equal to a target, for instance).

In general, such implementation details are not to be worried about. As long as you can implement the basic forms of binary search (finding an equal element in a sorted array, finding the smallest/largest value satisfying a condition), the specific ending condition that you use does not matter; any works. Instead, what matters is that you can tell what someone else's implementation of binary search is doing (which of the basic forms does it match), which mainly depends on how the l and r variables change in the loop instead of which of the three ending conditions the code's author happens to use.

»
9 months ago, # |
  Vote: I like it +11 Vote: I do not like it

It depends on how you want to access your final answer. There is no difference in the result. You should think through how the two implementations are different, but achieve the same result. For example, if you use while l <= r, where will the pointer be when you find your answer?

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

I think:

  • we will mostly use l <= r when in whole range we have only one possible answer

  • when the whole range contains many possible answer

  1. if you want to find maximum value in it we have to use r - l > 1 to avoid code running in infinite loop ,
  2. if you want to find minimum value in it we have to use l < r to avoid code running in infinite loop