-1

While binary search is a pretty algorithm, I've often found myself struggling with "off-by-1" issues for certain applications of binary search.

I have seen variants of binary search where it looks like one of the following 2:

while(lo <= hi)
{
  // do stuff
}

or

while(lo < hi)
{
  // do stuff
}

My impression has always been that you can use either, but the body of the while loop may change depending on which you use. Is this the correct interpretation?

roulette01
  • 1,984
  • 2
  • 13
  • 26

1 Answers1

0

A simple c# program to show the difference between '<' and '<=':

   byte a = 2;

            for(byte b=1; b<4; b++)
            {
                if (a < b)
                {
                    Console.WriteLine($"{a} is less then {b}");
                }
                else
                {
                    Console.WriteLine($"{a} is not less then {b}");
                }
                if (a <= b)
                {
                    Console.WriteLine($"{a} is less or equal to {b}");
                }
                else
                {
                    Console.WriteLine($"{a} is not less or equal to {b}");
                }
            }

output:

2 is not less then 1
2 is not less or equal to 1
2 is not less then 2
2 is less or equal to 2
2 is less then 3
2 is less or equal to 3
Luuk
  • 12,245
  • 5
  • 22
  • 33
  • 2
    What does this have to do with my question? I'm asking about the usage of each in the context of binary search. – roulette01 Sep 24 '20 at 19:02
  • If this has nothing to do with the question, then please add more info to your question or, ignore this because i did not understand your question. – Luuk Sep 25 '20 at 06:33