Skip to content
Shubham JangleResources
Search

Explore topics

Binary Search

Watch the walkthrough
Open on Instagram

Problem

Find target in an ascending sorted array and return its index, or -1 when absent.

Approach and revision checks

Maintain inclusive left/right boundaries; discard the half that cannot contain target. O(log n) time and O(1) space. Test empty input, first/last positions, and a missing value. Duplicate values may return any matching index; first/last occurrence needs a different boundary update. Prefer Math.floor(left + (right - left) / 2) to parseInt for computing an integer midpoint.

Original repository source

Copied from the supplied local DSA-Series checkout; code and comments are preserved. Run alternative definitions separately when comparing approaches.

11-binary-search.js

Original file on GitHub

var search = function (nums, target) {
  let i = 0;
  let j = nums.length - 1;

  while (i <= j) {
    let mid = parseInt((i + j) / 2);
    if (nums[mid] === target) return mid;

    if (nums[mid] < target) {
      i = mid + 1;
    } else {
      j = mid - 1;
    }
  }

  return -1;
};