What is the best way to search for an item in a sorted list in JavaScript?

When searching for an item in a sorted array in JavaScript, binary search is the most efficient approach. Unlike linear search which checks every element, binary search takes advantage of the sorted order to eliminate half the search space with each comparison.

What is Binary Search?

Binary search is a divide-and-conquer algorithm that works on sorted arrays. It compares the target value with the middle element and eliminates half of the remaining elements at each step. This approach has O(log n) time complexity, making it much faster than linear search's O(n).

How Binary Search Works

The algorithm follows these steps:

  1. Find the middle element of the array
  2. Compare it with the target value
  3. If equal, return the index
  4. If target is smaller, search the left half
  5. If target is larger, search the right half
  6. Repeat until found or search space is empty

Binary Search Implementation

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

    while (left <= right) {
        const middle = Math.floor((left + right) / 2);
        const middleElement = arr[middle];

        if (middleElement === target) {
            return middle; // Found the target
        } else if (middleElement < target) {
            left = middle + 1; // Search right half
        } else {
            right = middle - 1; // Search left half
        }
    }

    return -1; // Target not found
}

// Example usage
const sortedArray = [2, 4, 6, 8, 10, 12, 14, 16];
const target = 10;

const result = binarySearch(sortedArray, target);

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

Example with Different Scenarios

const numbers = [1, 3, 5, 7, 9, 11, 13, 15];

// Test different search cases
console.log("Searching for 7:", binarySearch(numbers, 7));   // Found
console.log("Searching for 1:", binarySearch(numbers, 1));   // First element
console.log("Searching for 15:", binarySearch(numbers, 15)); // Last element
console.log("Searching for 4:", binarySearch(numbers, 4));   // Not found
console.log("Searching for 20:", binarySearch(numbers, 20)); // Beyond range
Searching for 7: 3
Searching for 1: 0
Searching for 15: 7
Searching for 4: -1
Searching for 20: -1

Recursive Binary Search

function binarySearchRecursive(arr, target, left = 0, right = arr.length - 1) {
    if (left > right) {
        return -1; // Base case: target not found
    }

    const middle = Math.floor((left + right) / 2);

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

// Test recursive version
const data = [5, 10, 15, 20, 25, 30];
console.log("Recursive search for 20:", binarySearchRecursive(data, 20));
console.log("Recursive search for 8:", binarySearchRecursive(data, 8));
Recursive search for 20: 3
Recursive search for 8: -1

Performance Comparison

Algorithm Time Complexity Space Complexity Best For
Linear Search O(n) O(1) Unsorted arrays
Binary Search (Iterative) O(log n) O(1) Sorted arrays
Binary Search (Recursive) O(log n) O(log n) Sorted arrays

Key Points

  • Binary search requires the array to be sorted
  • It's significantly faster than linear search for large datasets
  • The iterative version uses constant space
  • Returns -1 when element is not found (common convention)
  • Works with any comparable data types (numbers, strings)

Conclusion

Binary search is the optimal way to search sorted arrays in JavaScript, offering O(log n) time complexity. Use the iterative version for better space efficiency, and always ensure your data is sorted before applying this algorithm.

Updated on: 2026-03-15T23:19:00+05:30

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements