Doubt in binary search

When we do binary search then we do

s = m + 1;
if the key > middle element

and s = m - 1
if the key < middle element

But this will work if the array is sorted in increasing order. We have to reverse the conditions if the array is sorted in decreasing order ? Please provide me the correct information ?

Hey @yashsharma4304

we do e=m-1 in 2nd case

Now talking about descending order

So if key >mid element then we do e=mid-1
else if key<mid element then we do s=mid+1

1 Like

we do e=m-1 in 2nd case
Ok, thank you for correcting me :slightly_smiling_face:

But if we want to write a code for both the cases (i.e. for the decreasing and increasing sorted array) then should I have to use if else ?

Yes ,u have to make changes in normal BS algo if u want to make common algo for both decreasing and increasing arrays.

If array is descending u can multiply all elements and key by -1 and it will become ascending then u can apply BS
or u can simply use of else and then apply BS according to if its ascending or descending .

If this resolves your query then please mark it as resolved :slight_smile:

1 Like