【问题标题】:When to use lo <= hi vs. lo < hi for binary search?何时使用 lo <= hi 与 lo < hi 进行二分搜索?
【发布时间】:2026-01-06 06:00:02
【问题描述】:

虽然二分搜索是一种漂亮的算法,但我经常发现自己在某些二分搜索应用中遇到“off-by-1”问题。

我见过二进制搜索的变体,它看起来像以下 2 之一:

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

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

我的印象一直是您可以使用其中任何一种,但while 循环的主体可能会根据您使用的方式而改变。这是正确的解释吗?

【问题讨论】:

标签: binary-search


【解决方案1】:

一个简单的 c# 程序来显示 '

   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}");
                }
            }

输出:

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

【讨论】:

  • 这与我的问题有什么关系?我在询问每个在二分搜索上下文中的用法。
  • 如果这与问题无关,请在您的问题中添加更多信息,或者忽略此问题,因为我不明白您的问题。