HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Using binary search to find the index to insert a number in a sorted JavaScript array

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptsortedinsertbinarysearchfindindextheusingnumber

Problem

In the past, I've tackled how to find the insertion index of an element in a sorted array, using Array.prototype.findIndex(). However, this approach has a time complexity of O(n), which is not ideal for large arrays. Naturally, when solving the same problem on LeetCode, I felt like I could do better, especially given the problem's O(n log n) time complexity constraint.
If you remember from a past article, the binary search algorithm is a fast and efficient way to find the index of an element in a sorted array. It works by repeatedly dividing the search interval in half, narrowing down the possible locations of the element.
@Quick refresher
The binary search algorithm's goal is to find the index of a given element in a sorted array. However, in this case, we want to find the index where we can insert a new element while maintaining the sorted order. The two problems are very similar in nature, so we can use the same algorithm with a few tweaks.
First, we'll implement the same while loop to narrow down the search interval. If we end up stumbling upon the exact same value, we can simply return the index of that value. Otherwise, we'll keep going until the loop termination condition is met. At that point, we can return the left boundary of the search interval, which will be the index where we can insert the new element.

Solution

@Quick refresher
The binary search algorithm's goal is to find the index of a given element in a sorted array. However, in this case, we want to find the index where we can insert a new element while maintaining the sorted order. The two problems are very similar in nature, so we can use the same algorithm with a few tweaks.
First, we'll implement the same while loop to narrow down the search interval. If we end up stumbling upon the exact same value, we can simply return the index of that value. Otherwise, we'll keep going until the loop termination condition is met. At that point, we can return the left boundary of the search interval, which will be the index where we can insert the new element.
```js {12}
const searchInsert = (arr, item) => {
let l = 0, r = arr.length - 1;

Context

From 30-seconds-of-code: binary-search-insert-index-sorted-number-array

Revisions (0)

No revisions yet.