Sometimes, we want to implement binary search in JavaScript.
In this article, we’ll look at how to implement binary search in JavaScript.
How to implement binary search in JavaScript?
To implement binary search in JavaScript, we can search for the index of the item according to the comparison of the item at different indexes starting at the middle of the array.
For instance, we write
const binarySearch = (arr, val) => {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === val) {
return mid;
}
if (val < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
};
to define the binarySearch
function.
In it, we define the start
and end
variables set to the first and last indexes of the sorted arr
array.
Then we use a while loop to search for the item as long as start
is less than or equal to end
.
We get the mid
array index with Math.floor
.
And we check if arr[mid]
is val
.
If it is, we return the mid
index.
If val
is less than arr[mid]
, then we set end
to mid - 1
to narrow down the search.
Otherwise, we set start
to mid + 1
to narrow down the search.
If nothing is found then -1 is returned.
Conclusion
To implement binary search in JavaScript, we can search for the index of the item according to the comparison of the item at different indexes starting at the middle of the array.