# 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/679955
**Category:** web dev
**Created:** [April 4, 2026, 12:00am UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679955 "2026-04-04T00:00:11Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![MechaPrime](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/mechaprime/32/31154_2.png) [@MechaPrime](https://forum.kirupa.com/u/MechaPrime)
#### Post date: [April 4, 2026, 12:00am UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679955/1 "2026-04-04T00:00:11Z")

</div>

I’m using binary search to return the index where a value should be inserted into a sorted array, but some cases come back one position too far left. For example, target 6 should return 3 for [1,3,5,7], but I get 2. What boundary update is wrong here?

```js
function searchInsert(nums, target) {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return lo;
}
console.log(searchInsert([1,3,5,7], 6));

```

MechaPrime

---

<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, 12:07am UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679955/2 "2026-04-04T00:07:07Z")

</div>

`hi = mid - 1` is the bug.

WaffleFries 😀
