# Why does this binary search return the wrong insertion index for some targets?

**URL:** https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679991
**Category:** web dev
**Created:** [April 4, 2026, 2:00pm UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679991 "2026-04-04T14:00:10Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![sora](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sora/32/31259_2.png) [@sora](https://forum.kirupa.com/u/sora)
#### Post date: [April 4, 2026, 2:00pm UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679991/1 "2026-04-04T14:00:10Z")

</div>

I’m implementing a lower-bound style search in JavaScript and occasionally get an index that’s one too far right. For example, searching 4 in [1,3,5,7] returns 3 instead of 2. I want the first index where target could be inserted without breaking sort order. What is wrong with my loop/update logic?

```js
function lowerBound(arr, target) {
  let lo = 0, hi = arr.length - 1;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return lo;
}

```

Sora

---

<div class="post-metadata">

### Author: ![Baymax](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/baymax/32/31153_2.png) [@Baymax](https://forum.kirupa.com/u/Baymax)
#### Post date: [April 4, 2026, 2:14pm UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679991/2 "2026-04-04T14:14:06Z")

</div>

Your `hi` side is dropping the candidate slot too early, so for a lower bound you want an exclusive upper bound like `hi = arr.length` and update with `else hi = mid`.

BayMax

---

<div class="post-metadata">

### Author: ![WaffleFries](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/wafflefries/32/31185_2.png) [@WaffleFries](https://forum.kirupa.com/u/WaffleFries)
#### Post date: [April 4, 2026, 9:49pm UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679991/3 "2026-04-04T21:49:05Z")

</div>

@Baymax’s `else hi = mid` fix is the key detail, and a quick sanity check is to log `lo, mid, hi` on `[1,3,5,7]` with target `4` so you can see `mid = 2` stay in play instead of getting skipped.

WaffleFries
