{"id":144,"date":"2026-11-13T12:32:38","date_gmt":"2026-11-13T04:32:38","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-binary-search-maintains-a-half-open-range\/"},"modified":"2026-11-13T21:51:14","modified_gmt":"2026-11-13T13:51:14","slug":"how-binary-search-maintains-a-half-open-range","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-binary-search-maintains-a-half-open-range\/","title":{"rendered":"How binary search maintains a half-open range"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Binary search<\/strong> keeps the invariant that a missing or matching key, if it is present, lies in a half-open index range [lo, hi). The midpoint is <strong>lo + (hi\u2212lo)\/\/2<\/strong>, which does not overflow when lo and hi are large. The loop that sets hi = mid when a[mid] \u2265 target returns the <strong>lower bound<\/strong>, the first index whose key is \u2265 the target. The search is <strong>\u0398(log n)<\/strong> comparisons on a sorted random-access array.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The array is sorted nondecreasing, and any item can be read by index in constant time. Each comparison must throw away a portion of the remaining range, and the portion thrown away must be unable to hide the answer. The bug that ships is almost always the range convention: inclusive bounds, a midpoint of (lo+hi) that overflows, or a lower bound used as if it were an equality test.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Lower bound answers a different question than &#8220;is the key present.&#8221; It returns the first legal insertion index. Equality is that index, checked against n and against the key stored there.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The loop invariant is: every index below lo holds a key &lt; target, and every index at or above hi holds a key \u2265 target. The range begins as [0, n). While lo &lt; hi the midpoint lies strictly inside, because hi\u2212lo \u2265 1 and the average rounds down. If a[mid] &lt; target then the answer is in [mid+1, hi). Otherwise the answer is in [lo, mid). When lo = hi, lo is the first index with a key \u2265 target, or n if every key is smaller. That is at most floor(log\u2082 n)+1 key comparisons.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The form lo+(hi\u2212lo)\/\/2 computes the same midpoint as (lo+hi)\/\/2 when the sum does not overflow a fixed-width index, and it stays inside the index type when lo and hi themselves are legal. An upper bound, the first key strictly greater than target, is the same loop with the test a[mid] \u2264 target advancing lo.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Set lo = 0 and hi = n on an array sorted nondecreasing.<\/li>\n<li>While lo &lt; hi, set mid = lo + (hi\u2212lo)\/\/2.<\/li>\n<li>If a[mid] &lt; target, set lo = mid+1. Otherwise set hi = mid.<\/li>\n<li>Return lo. This is the lower bound.<\/li>\n<li>The target is present only if lo &lt; n and a[lo] equals the target. The last equal key ends at the upper bound, computed by advancing lo when a[mid] \u2264 target.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The logarithmic bound needs random access and a sorted array. A linked list makes the midpoint expensive and the scan linear. An unsorted array makes the discarded half unsafe. A unimodal function, rather than a sorted array, is ternary search or a binary search on the slope.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the range invariant is broken<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>mid = (lo+hi)\/\/2 in a fixed-width integer<\/td>\n<td>When lo and hi are both large, the sum overflows, mid becomes negative or small, and the range does not shrink toward the target.<\/td>\n<\/tr>\n<tr>\n<td>Inclusive hi, with the loop condition lo \u2264 hi, and hi = mid\u22121 on a miss<\/td>\n<td>This form can be written correctly and is easy to write one off. The half-open loop has a single shrinking rule and returns the insertion index with no second case.<\/td>\n<\/tr>\n<tr>\n<td>Return mid as soon as a[mid] equals the target, from a lower-bound caller<\/td>\n<td>Equals may span a run. The first caller wanted the first equal, and an early return from a different loop answers an arbitrary equal.<\/td>\n<\/tr>\n<tr>\n<td>Binary search a rotated or unsorted array with this loop<\/td>\n<td>The test a[mid] &lt; target discards the left side only when the left side is known to be \u2264 a[mid]. Without sorted order that is false.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Finding a boundary in a monotonic predicate, such as the first index where a property becomes true, is the same loop with the predicate in place of a[mid] &lt; target. Searching an unordered array is linear search.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script binary-search a half-open range. <code>mid = lo + (hi-lo)\/\/2<\/code>, and a key that is not strictly smaller shrinks the high end. Both print the lower bound <code>1<\/code> of the value 2.<\/p>\n\n<pre><code class=\"language-bash\">a=(1 2 2 3)\ntarget=2\nlo=0\nhi=${#a[@]}\nwhile (( lo &lt; hi )); do\n  mid=$(( lo + (hi - lo) \/ 2 ))\n  if (( a[mid] &lt; target )); then lo=$((mid+1))\n  else hi=$mid; fi\ndone\necho &quot;$lo&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">a = [1, 2, 2, 3]\ntarget = 2\nlo, hi = 0, len(a)\nwhile lo &lt; hi:\n    mid = lo + (hi - lo) \/\/ 2\n    if a[mid] &lt; target:\n        lo = mid + 1\n    else:\n        hi = mid\nassert lo == 1 and a[lo] == 2\nprint(lo)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><code>git bisect<\/code> is binary search over commits. <code>bsearch<\/code>, C++ <code>lower_bound<\/code>, and Java <code>Arrays.binarySearch<\/code> are the same half-open walk on a sorted array. A hash table is the replacement when the keys are not ordered and only equality matters.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop binary search when the array is unsorted or is a linked list. Sort once if many queries will follow, or scan if they will not. Keep this half-open lower-bound loop whenever a sorted random-access array must yield a presence test or an insertion index in logarithmic comparisons.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for binary search returns the half-open lower-bound loop and the midpoint that does not add the endpoints. <strong>Binary search on a sorted array is the half-open loop that returns the first index whose key is at least the target, using a midpoint of lo plus half the width.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Binary search keeps the invariant that a missing or matching key, if it is present, lies in a half-open index range [lo, hi). The midpoint is lo + (hi\u2212lo)\/\/2, which does not overflow when lo and hi are large. The loop that sets hi = mid when&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,43],"tags":[],"class_list":["post-144","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-searching"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/144","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=144"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/144\/revisions"}],"predecessor-version":[{"id":543,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/144\/revisions\/543"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=144"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=144"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=144"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}