JavaScript Program to Implement Binary Search

JavaScript Program to Implement Binary Search

Binary Search is a fast and efficient searching algorithm that allows you to find an element in a sorted array quickly. Unlike Linear Search, which checks each element one by one, Binary Search repeatedly divides the array in half and checks the middle element. This “divide and conquer” approach makes it much faster, especially for large datasets.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Learning Binary Search is essential for beginners because it introduces fundamental algorithmic concepts like recursion, iteration, and the importance of sorted data. Binary Search is widely used in applications like searching in databases, looking up dictionary words, or finding items in a large inventory. By mastering this algorithm, beginners can gain confidence in solving problems efficiently in JavaScript.

Program 1: Iterative Binary Search

This program demonstrates Binary Search using a simple iterative approach with a while loop.

function binarySearchIterative(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; // Element found
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }

    }

    return -1; // Element not found

}

let numbers = [1, 3, 5, 7, 9, 11, 13];
let target = 7;
let result = binarySearchIterative(numbers, target);

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

This program works by repeatedly halving the array and checking the middle element. Beginners can understand it as “look in the middle, then decide to go left or right.” Iterative Binary Search is useful because it is simple, avoids recursion, and works efficiently on large arrays.

Program 2: Recursive Binary Search

This version demonstrates Binary Search using recursion instead of loops.

function binarySearchRecursive(arr, target, left = 0, right = arr.length - 1) {

    if (left > right) return -1;

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

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

}

let values = [2, 4, 6, 8, 10, 12, 14];
let searchTarget = 10;
let resultRecursive = binarySearchRecursive(values, searchTarget);

console.log(resultRecursive !== -1 ? `Element found at index ${resultRecursive}` : "Element not found");

This recursive approach works by checking the middle element and then calling the function again on the left or right half. Beginners can see recursion as a way to “break the problem into smaller pieces.” It is useful for learning recursion and understanding how divide-and-conquer algorithms work.

Program 3: Binary Search to find first occurrence

This example shows how to modify Binary Search to find the first occurrence of a target value in a sorted array with duplicates.

function binarySearchFirstOccurrence(arr, target) {

    let left = 0;
    let right = arr.length - 1;
    let result = -1;

    while (left <= right) {

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

        if (arr[mid] === target) {

            result = mid;
            right = mid - 1; // Search in left half for first occurrence

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

    }

    return result;

}

let duplicates = [1, 2, 2, 2, 3, 4, 5];
let targetDuplicate = 2;

console.log("First occurrence index:", binarySearchFirstOccurrence(duplicates, targetDuplicate));

This program works by continuing the search in the left half even after finding the target, ensuring the first occurrence is returned. Beginners can understand it as “keep looking left to find the first match.” It is useful in datasets where duplicate values exist.

Program 4: Binary Search to find last occurrence

This program demonstrates finding the last occurrence of a target value in a sorted array.

function binarySearchLastOccurrence(arr, target) {

    let left = 0;
    let right = arr.length - 1;
    let result = -1;

    while (left <= right) {

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

        if (arr[mid] === target) {

            result = mid;
            left = mid + 1; // Search in right half for last occurrence

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

    }

    return result;

}

let data = [5, 7, 7, 7, 8, 9, 10];
let targetValue = 7;

console.log("Last occurrence index:", binarySearchLastOccurrence(data, targetValue));

This program works similarly to the first occurrence search but continues searching the right half to find the last index. Beginners can understand it as “keep looking right to find the last match.” It is useful for counting duplicates or ranges in sorted arrays.

Program 5: Binary Search as a reusable function

This program wraps Binary Search into a clean utility function suitable for multiple datasets.

function binarySearchUtility(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;

}

let numbersSet = [3, 6, 9, 12, 15, 18];
let findNum = 12;
let resultUtility = binarySearchUtility(numbersSet, findNum);

console.log(resultUtility !== -1 ? `Element found at index ${resultUtility}` : "Element not found");

This reusable function allows beginners to perform Binary Search efficiently in any project. It demonstrates the best practice of creating clean, modular code while leveraging the speed of Binary Search.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Binary Search in JavaScript in simple terms.

Q1. What is Binary Search in JavaScript?
Binary Search is a fast searching algorithm that finds a target element in a sorted array by repeatedly dividing the search range in half.

Q2. Can Binary Search be used on unsorted arrays?
No, Binary Search requires a sorted array to work correctly.

Q3. What is the time complexity of Binary Search?
The time complexity is O(log n), which is much faster than Linear Search for large datasets.

Q4. Can Binary Search handle duplicate elements?
Yes, with modifications, Binary Search can find the first or last occurrence of duplicates.

Q5. Why should beginners learn Binary Search?
It teaches the divide-and-conquer approach, efficient searching, recursion, and practical problem-solving in JavaScript.

Conclusion

Binary Search is a fundamental algorithm that every beginner should master. It demonstrates how sorting and divide-and-conquer strategies can make searching much faster than checking elements one by one.

By practicing iterative and recursive implementations, as well as first and last occurrence searches, beginners gain valuable skills in algorithm design, recursion, and handling sorted datasets. Mastering Binary Search in JavaScript strengthens your foundation for more advanced algorithms and efficient programming practices.

Scroll to Top