Code Snippets
/

Binary Search Template

Binary Search Template

Binary search is the most asked algorithm in interviews and the easiest to get wrong: off-by-one bugs, infinite loops, integer overflow on the midpoint. This snippet covers the iterative bounds template that always terminates, a recursive variant for contrast, and a found-or-insertion-point version that returns where the value would go if absent. The same skeleton powers the lower-bound and upper-bound variants in the next entry.

JavaScript
Easy
3 snippets
algorithms
binary-search
code-template
two-pointers

968 views

17

function binarySearch(arr, target) {
    let lo = 0;
    let hi = arr.length - 1;
    while (lo <= hi) {
        const mid = (lo + hi) >>> 1;
        if (arr[mid] === target) return mid;
        if (arr[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

console.log(binarySearch([1, 3, 5, 7, 9, 11], 7)); // 3
console.log(binarySearch([1, 3, 5, 7, 9, 11], 4)); // -1
console.log(binarySearch([], 1));                  // -1

The closed-interval template uses lo <= hi and updates with mid + 1 and mid - 1. The two updates are what guarantee termination: every iteration removes at least one index from consideration. Using (lo + hi) >>> 1 is the safe midpoint formula in JavaScript: the unsigned right shift avoids overflow that the equivalent (lo + hi) / 2 would suffer in languages with fixed-width integers. Time complexity is O(log n) and space is O(1). Memorise this exact shape; almost every binary search variant is one of these three lines changed.