ALGORITHMS_TODAY.COM
◄ BACK_TO_INDEX.exe
[SEARCHING] MODULE LOADED

BINARY_SEARCH

Divide the sorted array in half each time. Logarithmic efficiency hiding in plain sight.

TIME_COMPLEXITY
O(log n)
SPACE_COMPLEXITY
O(1)
DIFFICULTY
BASIC
PROCESS: BINARY_SEARCH.exe■ COMPLETE
> step[001/000]
██ IN-WINDOW██ COMPARE (mid)██ ELIMINATED██ FOUND
▲ LO / ▲ HI carets #00e5ff · ▲ MID caret #ffe600 · ⟦ ⟧ WINDOW bracket + tint · - - TARGET reference line
CLOCK_SPEED
TARGET0
DECRYPTED_SOURCE.js● LIVE
// BINARY_SEARCH.js — O(log n) time complexity
// Precondition: arr must be sorted in ascending order.
function binarySearch(arr, target) {
  let lo = 0;
  let hi = arr.length - 1;

  while (lo <= hi) {
    // Midpoint, written to avoid overflow on huge arrays
    const mid = lo + Math.floor((hi - lo) / 2);

    if (arr[mid] === target) {
      return mid; // Found — DECODED
    } else if (arr[mid] < target) {
      lo = mid + 1; // Target must be in the right half
    } else {
      hi = mid - 1; // Target must be in the left half
    }
  }

  return -1; // Not present
}
DECRYPTED_LOGIC.txt
01Requires the input array to be sorted in ascending order
02Compare the target against the middle element of the range
03On a match, return the middle index — the target is found
04If the target is larger, discard the left half; else the right
05Repeat on the halved range until found or the range is empty