pattrick james
pattrick james

Reputation: 105

Start, end and stopping condition of Binary Search code

I hope everyone is doing well.

I know there are a lot of questions whose title is very much similar to my question but I have a doubt regarding start and end values :-

Thanks for spending your precious time in solving my query.

I hope I've written clearly.

Upvotes: 0

Views: 869

Answers (1)

trincot
trincot

Reputation: 350756

If I use stopping condition as start<=end then, whether start=0 ,end=n/n-1|start=-1,end=n-1/n|start=-2 to end=n-2| start=-3 to end=n-3 the output is same in all these cases for the below code.

This is not true. start and end must start at precisely the first and last index of the array, or there will be cases where the algorithm you provided fails. So assuming zero-based array indexing, start = 0, end = n - 1 is the only correct initialisation for this algorithm.

Here are counter examples for some alternatives:

  • start = 0, end = n: if k is a value that is greater than the greatest value in arr, then eventually mid will become equal to n and arr[mid] will be an invalid reference. Depending on the language this may trigger an exception.

  • start = -1, end = n - 1: if k is a value that is less than the least value in arr, then eventually mid will become equal to -1 and arr[mid] will be an invalid reference.

  • start = -2, end = n - 2. if k == arr[0] and n == 3, the element will not be found, as mid will get the value -1.

  • start = -2, end = n + 2. if k == arr[0] and n == 3, the element will not be found, as mid will get the value 1 and in the next iteration it will be -1, so skipping for ever the index 0.

  • ...etc

Upvotes: 1

Related Questions