Write a program binary search in JavaScript?
Binary search is an efficient algorithm for finding an item from a sorted list of items. The basic idea behind binary search is to divide the list into halves repeatedly until the desired item is found or it is determined that the item is not in the list.
The algorithm starts by comparing the middle item of the list with the target item. If the middle item is equal to the target, the search is complete and the index of the item is returned. If the target is less than the middle item, the search continues in the lower half of the list. If the target is greater than the middle item, the search continues in the upper half of the list. This process is repeated until the target item is found or it is determined that the item is not in the list.
Binary search is more efficient than linear search, which checks each item in the list one by one, because binary search divides the list into halves and discards half of the list in each step. The time complexity of binary search is O(log n), where n is the number of items in the list.
Here’s an implementation of binary search in JavaScript:
function binarySearch(array, target) {
let start = 0;
let end = array.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (array[mid] === target) {
return mid;
} else if (array[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
This function takes in an array
and a target
as inputs, and returns the index of the target in the array if it exists, or -1 if it does not.
Note: This implementation assumes that the input array is sorted in ascending order.