ArticleZip > Binary Search In Javascript

Binary Search In Javascript

Binary Search in JavaScript

Binary search is a popular algorithm used for searching elements in a sorted array. It has a time complexity of O(log n), making it much more efficient than a linear search. If you're working on a project that requires fast searching of data and are looking to implement binary search in JavaScript, you've come to the right place. In this article, we'll walk you through the process of implementing a binary search algorithm in JavaScript step by step.

Before we start coding, let's understand the concept of binary search. Binary search works by repeatedly dividing the array in half and then narrowing down the search by comparing the middle element with the target value. If the middle element matches the target, the search is successful. If the target is less than the middle element, the search continues on the left half of the array; if it's greater, the search moves to the right half.

Here's a simple implementation of binary search in JavaScript:

Javascript

function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;

    while (left <= right) {
        let mid = Math.floor((left + right) / 2);

        if (arr[mid] === target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1; // Target not found
}

let array = [2, 4, 6, 8, 10, 12, 14];
let target = 8;
let result = binarySearch(array, target);

if (result !== -1) {
    console.log(`Element found at index: ${result}`);
} else {
    console.log('Element not found');
}

In this code snippet, we define a function `binarySearch` that takes an array `arr` and a target value to search for. We initialize `left` and `right` pointers to track the search boundaries. The `while` loop iterates until the search is narrowed down to a single element or the target is found.

The `mid` index is calculated as the midpoint between the `left` and `right` indices. We compare the element at index `mid` with the target value. If they match, we return the index. If the element is less than the target, we update the `left` pointer to `mid + 1` to search in the right half; otherwise, we update the `right` pointer to `mid - 1` to search in the left half.

After implementing the binary search algorithm, we test it with a sample sorted array `[2, 4, 6, 8, 10, 12, 14]` and a target value of `8`. If the target is found, the function returns the index of the element; otherwise, it returns -1.

Binary search is a powerful algorithm for efficiently searching sorted arrays. By understanding how binary search works and implementing it in JavaScript, you can enhance the performance of your applications that require fast searching of data. Experiment with different arrays and target values to deepen your understanding of binary search and its applications in real-world scenarios. Happy coding!